Time Conversion Algorithm in Javascript
2 min readJan 31, 2021
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Note: — 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
- 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
Example
- Return ‘12:01:00’.
- Return ‘00:01:00’.
Function Description
Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.
timeConversion has the following parameter(s):
- string s: a time in hour format
Returns
- string: the time in hour format
Input Format
A single string that represents a time in -hour clock format (i.e.: or ).
Constraints
- All input times are valid
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
I recently came across this algorithm on HackerRank.com and decided to do a short break down on my solution.
- The first step is to break the input string down into something easier to work with. For this, we will use .slice() to take only the first 8 characters, as well as .split to break each section (hh/mm/ss) into separate integers.
- Next, we will take to original input string and call indexOf() to determine if it is AM or PM. With .indexOf(), it is important to remember that if the argument is NOT found, the index returned will be -1.
- In this challenge, the only conversion we need to make is in the case of a PM time, we must add 12 to that number. We can convert this into a ternary rather than an if statement, but we need to remember that it is possible for 12PM to occur. In the 12PM hour, we will not want to add +12 to the original output.
- Once this is done, we can simply use a .join() call to get our output where we want it!