Skip to content

Commit 5cecbee

Browse files
Fix hour formatting using padStart
1 parent 73874a4 commit 5cecbee

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

Sprint-2/5-stretch-extend/format-time.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
function formatAs12HourClock(time) {
66
const hours = Number(time.slice(0, 2));
77
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
8+
time = hours - 12;
9+
return `${time.toString().padStart(2 , "0")}:00 pm`
910
}
1011
return `${time} am`;
1112
}
@@ -23,3 +24,24 @@ console.assert(
2324
currentOutput2 === targetOutput2,
2425
`current output: ${currentOutput2}, target output: ${targetOutput2}`
2526
);
27+
const currentOutput3 = formatAs12HourClock("19:00");
28+
const targetOutput3 = "07:00 pm";
29+
console.assert(
30+
currentOutput3 === targetOutput3,
31+
`current output: ${currentOutput3}, target output: ${targetOutput3}`
32+
);
33+
34+
const currentOutput4 = formatAs12HourClock("21:00");
35+
const targetOutput4 = "09:00 pm";
36+
console.assert(
37+
currentOutput4 === targetOutput4,
38+
`current output: ${currentOutput4}, target output: ${targetOutput4}`
39+
);
40+
41+
42+
43+
// The previous version only worked properly for two-digit hours. To fix this, I made sure the hour is always displayed in two-digit format.
44+
45+
// First, I completed the mathematical calculation and stored the result in a variable. Then, I converted it to a string and used padStart(2, "0") to add a leading zero when needed.
46+
47+
// Now, it works correctly for all times greater than 12 and always shows two digits.

0 commit comments

Comments
 (0)