My approach to solving HackerRank’s Time Conversion code challenge.
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
s = "12:01:00PM"
Return '12:01:00'
.
s = "12:01:00AM"
Return '00:01:00'
.
A single string s
that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM
or hh:mm:ssPM
).
Return the time in 24 hour format string.
107:05:45PM
119:05:45
We use String.split()
by :
on the given time
string to convert it into a temporary array (tmp
).
After that, we extract hours (h
), minutes (m
), and seconds (s
).
While the extraction, we use Number()
to convert the hours' value from string to number and the String.slice()
method to extract seconds without the AM
/PM
indicator.
Then we use the Array.includes()
method to check out whenever it's a PM
indicator and store the results in a boolean variables isPm
.
After the data extraction, we need to understand how many conversion cases we need to cover. Following the example in the code challenge description, I come up with the following:
12:01:00PM
=> 12:01:00
12:01:00AM
=> 00:01:00
01:01:00AM
=> 01:01:00
or 11:01:00AM
=> 11:01:00
07:01:00PM
=> 19:01:00
Implementation starts with the convert()
function creation which accepts the hour (h
) value as a parameter. Usingif
statements, we evaluate the existing values for hours (h
) and the isPm
indicator and return the relevant hour value for each case.
Finally, we return a string with a new converted date.
1function timeConversion(time) {2 const tmp = time.split(':');3 const h = Number(tmp[0]),4 m = tmp[1],5 s = tmp[2].slice(0, 2);6 const isPm = tmp[2].includes('PM') ? true : false;7
8 const convert = (h) => {9 // 12:01:00PM => 12:01:0010 if (h === 12 && isPm) {11 return 12;12 }13
14 // 12:01:00AM => 00:01:0015 if (h === 12 && !isPm) {16 return '00';17 }18
19 // 01:01:00AM => 01:01:0020 // 11:01:00AM => 11:01:0021 if (!isPm) {22 return h < 10 ? `0${h}` : h;23 }24
25 // 07:01:00PM => 19:01:0026 return h + 12;27 };28
29 return `${convert(h)}:${m}:${s}`;30}
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter