Skip to content

Commit 9240183

Browse files
committed
improved time validation and formatting logic
1 parent 6a11e56 commit 9240183

1 file changed

Lines changed: 22 additions & 11 deletions

File tree

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
11
function formatAs12HourClock(time) {
2-
const hours = Number(time.slice(0, 2));
2+
const slicedHours = time.slice(0, 2);
3+
const hours = Number(slicedHours);
34
const slicedMinutes = time.slice(-2);
5+
const minutes = Number(slicedMinutes);
6+
const pattern = /^\d{2}:\d{2}$/;
47

5-
if (hours === 0) {
6-
return `12:${slicedMinutes} am`;
7-
} else if (hours > 1 && hours <= 11) {
8-
return `0${hours}:${slicedMinutes} am`;
9-
} else if (hours === 12) {
10-
return `12:${slicedMinutes} pm`;
11-
} else if (hours > 12 && hours <= 21) {
12-
return `0${hours - 12}:${slicedMinutes} pm`;
13-
} else if (hours === 22 || hours === 23) {
14-
return `${hours - 12}:${slicedMinutes} pm`;
8+
if (typeof time === "string" && pattern.test(time)) {
9+
if (minutes < 60) {
10+
if (hours < 24) {
11+
if (hours === 0) {
12+
return `12:${slicedMinutes} am`;
13+
} else if (hours === 12) {
14+
return `${hours}:${slicedMinutes} pm`;
15+
} else if (hours > 12) {
16+
return `${(hours - 12).toString().padStart(2, "0")}:${slicedMinutes} pm`;
17+
} else {
18+
return `${time} am`;
19+
}
20+
}
21+
22+
return `Please check your HH input must be less than 24`;
23+
}
24+
return `Please check your MM input must be less than 60`;
1525
}
26+
return `Please check your format input must be 'HH:MM'`;
1627
}
1728

1829
export { formatAs12HourClock };

0 commit comments

Comments
 (0)