Skip to content

Commit 8b3befa

Browse files
Fix 12-hour clock formatting
1 parent 4f1e07c commit 8b3befa

1 file changed

Lines changed: 41 additions & 7 deletions

File tree

‎Sprint-3/5-stretch-extend/format-time.js‎

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,56 @@
44

55
function formatAs12HourClock(time) {
66
const hours = Number(time.slice(0, 2));
7+
if (hours === 0) {
8+
return `12${time.slice(2)} am`;
9+
}
10+
if (hours === 12) {
11+
return `12${time.slice(2)} pm`;
12+
}
713
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
14+
return `${String(hours - 12).padStart(2, "0")}:${time.slice(3)} pm`;
915
}
1016
return `${time} am`;
1117
}
1218

13-
const currentOutput = formatAs12HourClock("08:00");
14-
const targetOutput = "08:00 am";
19+
const currentOutput = formatAs12HourClock("08:30");
20+
const targetOutput = "08:30 am";
1521
console.assert(
1622
currentOutput === targetOutput,
17-
`current output: ${currentOutput}, target output: ${targetOutput}`
23+
`current output: ${currentOutput}, target output: ${targetOutput}`,
1824
);
1925

20-
const currentOutput2 = formatAs12HourClock("23:00");
21-
const targetOutput2 = "11:00 pm";
26+
const currentOutput2 = formatAs12HourClock("15:30");
27+
const targetOutput2 = "03:30 pm";
2228
console.assert(
2329
currentOutput2 === targetOutput2,
24-
`current output: ${currentOutput2}, target output: ${targetOutput2}`
30+
`current output: ${currentOutput2}, target output: ${targetOutput2}`,
2531
);
32+
33+
const currentOutput5 = formatAs12HourClock("11:59");
34+
const targetOutput5 = "11:59 am";
35+
console.assert(
36+
currentOutput5 === targetOutput5,
37+
`current output: ${currentOutput5}, target output: ${targetOutput5}`,
38+
);
39+
40+
const currentOutput3 = formatAs12HourClock("00:00");
41+
const targetOutput3 = "12:00 am";
42+
43+
console.assert(
44+
currentOutput3 === targetOutput3,
45+
`current output: ${currentOutput3}, target output: ${targetOutput3}`,
46+
);
47+
const currentOutput4 = formatAs12HourClock("12:02");
48+
const targetOutput4 = "12:02 pm";
49+
50+
console.assert(
51+
currentOutput4 === targetOutput4,
52+
`current output: ${currentOutput4}, target output: ${targetOutput4}`,
53+
);
54+
55+
console.log(currentOutput, targetOutput);
56+
console.log(currentOutput2, targetOutput2);
57+
console.log(currentOutput3, targetOutput3);
58+
console.log(currentOutput4, targetOutput4);
59+
console.log(currentOutput5, targetOutput5);

0 commit comments

Comments
 (0)