Converting 12 hour format time to 24 hour format in JavaScript


We are required to write a JavaScript function that takes in a time string in the following format −

const timeStr = '05:00 PM';

Note that the string will always be of the same format i.e.

HH:MM mm

Our function should make some computations on the string received and then return the corresponding 24 hour time in the following format: HH:MM

For example:

For the above string, the output should be −

const output = '17:00';

Example

The code for this will be −

 Live Demo

const timeStr = '05:00 PM';
const secondTimeStr = '11:42 PM';
const convertTime = timeStr => {
   const [time, modifier] = timeStr.split(' ');
   let [hours, minutes] = time.split(':');
   if (hours === '12') {
      hours = '00';
   }
   if (modifier === 'PM') {
      hours = parseInt(hours, 10) + 12;
   }
   return `${hours}:${minutes}`;
};
console.log(convertTime(timeStr));
console.log(convertTime(secondTimeStr));

Output

And the output in the console will be −

17:00
23:42

Updated on: 22-Feb-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements