Skip to content

Edvins Antonovs

Time Conversion code challenge

My approach to solving HackerRank’s Time Conversion code challenge.


Problem

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Example

s = "12:01:00PM"

Return '12:01:00'.

s = "12:01:00AM"

Return '00:01:00'.

Input format

A single string s that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM).

Output format

Return the time in 24 hour format string.

Sample input

107:05:45PM

Sample output

119:05:45

Solution

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:

  • midday 12:01:00PM => 12:01:00
  • midnight 12:01:00AM => 00:01:00
  • morning 01:01:00AM => 01:01:00 or 11:01:00AM => 11:01:00
  • evening 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:00
10 if (h === 12 && isPm) {
11 return 12;
12 }
13
14 // 12:01:00AM => 00:01:00
15 if (h === 12 && !isPm) {
16 return '00';
17 }
18
19 // 01:01:00AM => 01:01:00
20 // 11:01:00AM => 11:01:00
21 if (!isPm) {
22 return h < 10 ? `0${h}` : h;
23 }
24
25 // 07:01:00PM => 19:01:00
26 return h + 12;
27 };
28
29 return `${convert(h)}:${m}:${s}`;
30}

Appendix

Subscribe to the newsletter

Get emails from me about web development, tech and entrepreneurship.

© 2022 by Edvins Antonovs. All rights reserved.