Solving one of the challenges from HackerRank with JavaScript
First, what is HackerRank? It is website for us — developers that provide many challenges so we can train there in programming on different languages. As I am an front-end dev — I pick JavaScript, but it’s up to you.
Time Conversion
Our challenge — is to convert 12-hour time format into 24-hour format. We’ve got some random input like 07:05:45PM
and our target is to return 19:05:45
as output.
How we can achieve this? We need to understand - is it PM
or AM
, with JS it’s pretty easy with string method indexOf.
Next we need to change numbers according to period. But we can’t directly change strings in JavaScript! So let’s use helpful split method and create new array. Plus let’s get rid of PM
AM
postfix.
At this moment we have just enough to write some conversion logic! Only difference between 12h and 24h formats is hours, minutes and seconds are the same, so we need to change only first value in our array. More about conversion logic you can read on wikipedia.
Looks pretty ugly, right? We’ll rewrite it next using ternary operator. Probably it’s not the best solution, but it looks pretty minimal.
Here is the final step. Now we can place all our code together!
Ohhh, wait, didn’t we forget something? Yes we forgot to join our array into string and here goes join method.
That’s it! This is our final 5-lines code that can convert 12-hour time format into 24-hour format!