Skip to content

Commit a9c2a21

Browse files
committed
format 12-hour time consistently with 2-digit hours
1 parent f63026f commit a9c2a21

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

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

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,33 @@ function formatAs12HourClock(time) {
22
const hours = Number(time.slice(0, 2));
33
const minutes = time.slice(3, 5);
44

5+
let formattedHour;
6+
let period;
7+
58
if (hours === 0) {
6-
// midnight
7-
return `12:${minutes} am`;
9+
formattedHour = "12";
10+
period = "am";
811
} else if (hours === 12) {
9-
// noon
10-
return `12:${minutes} pm`;
12+
formattedHour = "12";
13+
period = "pm";
1114
} else if (hours > 12) {
12-
return `${hours - 12}:${minutes} pm`;
15+
formattedHour = String(hours - 12).padStart(2, "0");
16+
period = "pm";
1317
} else {
14-
// 1am to 11am
15-
return `${time} am`;
18+
formattedHour = String(hours).padStart(2, "0");
19+
period = "am";
1620
}
21+
22+
return `${formattedHour}:${minutes} ${period}`;
1723
}
1824

25+
1926
// Tests:
2027
const tests = [
2128
{ input: "00:00", expected: "12:00 am" },
2229
{ input: "08:00", expected: "08:00 am" },
2330
{ input: "12:00", expected: "12:00 pm" },
24-
{ input: "15:30", expected: "3:30 pm" },
31+
{ input: "15:30", expected: "03:30 pm" },
2532
{ input: "23:59", expected: "11:59 pm" },
2633
{ input: "11:15", expected: "11:15 am" },
2734
];
@@ -34,3 +41,4 @@ tests.forEach(({ input, expected }) => {
3441
);
3542
});
3643

44+

0 commit comments

Comments
 (0)