Time conversion

Klecianny Melo - Mar 1 - - Dev Community

Prepare your favorite cup of coffee because we are about to enter the fantastic world of Time conversion.

What is a time conversion?

A time is represented in the format 12 hours, of hh:mm:ssAM/PM. We must convert to 24-hour format. If the time is 12:00:00AM, it will be represented as 00:00:00. If the time is 12:00:00PM, it will be represented as 12:00:00.

Image description

Let's learn how to convert a time from hh:mm:ssAM/PM to hh:mm:ss.

If we have the time 07:05:45PM, we should return 19:05:45

const s = '07:05:45PM';
Enter fullscreen mode Exit fullscreen mode

The first step is to divide the time into parts, for this we will use the slice method which will limit the time string to 8 positions, so as not to consider the suffix AM or PM.

s.slice(0,8) // '07:05:45'
Enter fullscreen mode Exit fullscreen mode

Now we must obtain the hour, minute and second, for this we will use the split method and pass the : parameter so that the positions of the hours, minutes and seconds are separated.

s.slice(0,8).split(':') // ['07', '05', '45']
Enter fullscreen mode Exit fullscreen mode

Since we already have the hour, minute and second, we will assign constants to collect each value

const [hour, minute, second] = s.slice(0,8).split(':');
// hour = '07'
// minute = '05'
// second = '45'
Enter fullscreen mode Exit fullscreen mode

In this problem, it will only be necessary to modify the hour value to convert AM/PM to 24-hour format. So let's check if the time string has PM in its structure

s.includes('PM') // true
Enter fullscreen mode Exit fullscreen mode

The includes method will return true if the value is contained in the string and false if the value is not contained in the string

If the hour string has the PM we will convert the format from 12 hours to 24 hours as follows:

hour == 12 ? '12' : Number(hour) + 12
Enter fullscreen mode Exit fullscreen mode

If the time is 12PM, it will continue with the number 12. For other cases we will add 12 units to the hour.

When the time is AM, we will have the following validation:

hour == 12 ? '00' : hour
Enter fullscreen mode Exit fullscreen mode

For 12AM we will consider the value 00. For other values the time will remain the same.

Finally, we simply return a string concatenating the converted hour, minute and second

return `${hour}:${minute}:${second}`
Enter fullscreen mode Exit fullscreen mode

Our final resolution to the problem is:

const s = '07:05:45PM';

const [hour, minute, second] = s.slice(0,8).split(':');

hour = s.includes('PM') ?
    (hour == 12 ? '12' : Number(hour) + 12) :
    (hour == 12 ? '00' : hour);

return `${hour}:${minute}:${second}`;
Enter fullscreen mode Exit fullscreen mode

Share the code, spread knowledge and build the future! šŸ˜‰

Image generated by DALLĀ·E 3

. . . . . . . . . . . . . . . . . . . . . . . .