44
55function formatAs12HourClock ( time ) {
66 const hours = Number ( time . slice ( 0 , 2 ) ) ;
7- if ( hours > 12 ) {
8- return `${ hours - 12 } :00 pm` ;
7+ const minutes = time . slice ( 3 ) ;
8+
9+ if ( hours === 0 ) {
10+ return `12:${ time . slice ( 3 ) } am` ;
11+ }
12+ else if ( hours < 12 ) {
13+ return `${ time } am` ;
14+ }
15+ else if ( hours <= 12 ) {
16+ return `${ time } pm` ;
17+ }
18+ else if ( hours > 12 ) {
19+ return `${ String ( hours - 12 ) . padStart ( 2 , "0" ) } :${ minutes } pm` ;
920 }
10- return `${ time } am` ;
21+ else if ( hours > 12 ) {
22+ return `${ hours - 12 } :${ minutes } pm` ;
23+ }
24+ else if ( hours < 12 ) {
25+ return `${ time } :${ minutes } am` ;
26+ }
1127}
12-
1328const currentOutput = formatAs12HourClock ( "08:00" ) ;
1429const targetOutput = "08:00 am" ;
1530console . assert (
1631 currentOutput === targetOutput ,
1732 `current output: ${ currentOutput } , target output: ${ targetOutput } `
1833) ;
34+ console . log ( formatAs12HourClock ( "08:00" ) ) ;
1935
2036const currentOutput2 = formatAs12HourClock ( "23:00" ) ;
2137const targetOutput2 = "11:00 pm" ;
2238console . assert (
2339 currentOutput2 === targetOutput2 ,
2440 `current output: ${ currentOutput2 } , target output: ${ targetOutput2 } `
2541) ;
42+ console . log ( formatAs12HourClock ( "23:00" ) ) ;
43+
44+ const currentOutput3 = formatAs12HourClock ( "00:00" ) ;
45+ const targetOutput3 = "12:00 am" ;
46+ console . assert (
47+ currentOutput3 === targetOutput3 ,
48+ `current output: ${ currentOutput3 } , target output: ${ targetOutput3 } `
49+ ) ;
50+ console . log ( formatAs12HourClock ( "00:00" ) ) ;
51+
52+ const currentOutput4 = formatAs12HourClock ( "23:59" ) ;
53+ const targetOutput4 = "11:59 pm" ;
54+ console . assert (
55+ currentOutput4 === targetOutput4 ,
56+ `current output: ${ currentOutput4 } , target output: ${ targetOutput4 } `
57+ ) ;
58+ console . log ( formatAs12HourClock ( "23:59" ) ) ;
59+
60+ const currentOutput5 = formatAs12HourClock ( "12:00" ) ;
61+ const targetOutput5 = "12:00 pm" ;
62+ console . assert (
63+ currentOutput5 === targetOutput5 ,
64+ `current output: ${ currentOutput5 } , target output: ${ targetOutput5 } `
65+ ) ;
66+ console . log ( formatAs12HourClock ( "12:00" ) ) ;
67+
68+ const currentOutput6 = formatAs12HourClock ( "13:00" ) ;
69+ const targetOutput6 = "01:00 pm" ;
70+ console . assert (
71+ currentOutput6 === targetOutput6 ,
72+ `current output: ${ currentOutput6 } , target output: ${ targetOutput6 } `
73+ ) ;
74+ console . log ( formatAs12HourClock ( "13:00" ) ) ;
75+
76+ const currentOutput7 = formatAs12HourClock ( "11:59" ) ;
77+ const targetOutput7 = "11:59 am" ;
78+ console . assert (
79+ currentOutput7 === targetOutput7 ,
80+ `current output: ${ currentOutput7 } , target output: ${ targetOutput7 } `
81+ ) ;
82+ console . log ( formatAs12HourClock ( "11:59" ) ) ;
0 commit comments