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.
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!
Gurupriyan is a Software Engineer and a technology enthusiast, he’s been working on the field for the last 6 years. Currently focusing on mobile app development and IoT.