Skip to content

Commit b507572

Browse files
committed
Refactor formatAs12HourClock function to correctly convert 24-hour time to 12-hour format with proper padding and period indication
1 parent 7d51222 commit b507572

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

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

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,24 @@
33
// Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find.
44

55
function formatAs12HourClock(time) {
6-
const hours = Number(time.slice(0, 2));
7-
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
6+
let hours = Number(time.slice(0, 2)); // if its const it will throe an TypeError you cant assign a const variable later on
7+
const minutes = time.slice(3, 5);
8+
9+
10+
// for am and pm periods
11+
const period = hours >= 12 ? "pm" : "am"; // if hours is greater than or equal to 12, it's pm, otherwise it's am
12+
13+
// to convert hours from 24-hour format to 12-hour format
14+
if (hours === 0) {
15+
hours = 12; // if hours is 0, it should be 12 in 12-hour format
16+
} else if (hours > 12) {
17+
hours = hours - 12;
918
}
10-
return `${time} am`;
19+
20+
// for format hours to always be 2 digits
21+
const padHours = hours.toString().padStart(2, "0");
22+
23+
return `${padHours}:${minutes} ${period}`;
1124
}
1225

1326
const currentOutput = formatAs12HourClock("08:00");
@@ -23,3 +36,24 @@ console.assert(
2336
currentOutput2 === targetOutput2,
2437
`current output: ${currentOutput2}, target output: ${targetOutput2}`
2538
);
39+
40+
const currentOutput3 = formatAs12HourClock("12:00");
41+
const targetOutput3 = "12:00 pm";
42+
console.assert(
43+
currentOutput3 === targetOutput3,
44+
`current output: ${currentOutput3}, target output: ${targetOutput3}`
45+
);
46+
47+
const currentOutput4 = formatAs12HourClock("00:00");
48+
const targetOutput4 = "12:00 am";
49+
console.assert(
50+
currentOutput4 === targetOutput4,
51+
`current output: ${currentOutput4}, target output: ${targetOutput4}`
52+
);
53+
54+
const currentOutput5 = formatAs12HourClock("13:20");
55+
const targetOutput5 = "01:20 pm";
56+
console.assert(
57+
currentOutput5 === targetOutput5,
58+
`current output: ${currentOutput5}, target output: ${targetOutput5}`
59+
);

0 commit comments

Comments
 (0)