Time conversion
Klecianny Melo

Klecianny Melo @kecbm

About: 💻 Software Engineer | SWE | ⚙️ JavaScript, .NET, React, Docker, Node.js, CSS | 📝 Author

Location:
Garanhuns, Pernambuco
Joined:
Apr 13, 2022

Time conversion

Publish Date: Mar 1 '24
71 23

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

Comments 23 total

  • Renato Teixeira
    Renato TeixeiraMar 1, 2024

    really interesting! I'll try this algorithm soon :D

  • Rayanny Bezerra
    Rayanny BezerraMar 1, 2024

    Great article, study leetcode is a key of success!

    • Klecianny Melo
      Klecianny MeloMar 1, 2024

      Sounds great! Thank you for this contribution Ray ❤️

  • Anthony Vinicius
    Anthony ViniciusMar 1, 2024

    Working with time is so complex... Great content!!

    • Klecianny Melo
      Klecianny MeloMar 1, 2024

      It's true, it's one of the complex issues we have in algorithms. Thanks my friend!

  • Guimo
    GuimoMar 2, 2024

    Love it! working with time can be a great headache, a great and very useful article.

    • Klecianny Melo
      Klecianny MeloMar 2, 2024

      It's true, time is a sensitive topic in terms of code. Thank you very much! 😁

  • James Larsen
    James LarsenMar 4, 2024

    How does the 3rd line compile if 'hour' is a constant?

    • Klecianny Melo
      Klecianny MeloMar 4, 2024

      Hello @jdlarsen1945, how are you? In JavaScript, the const keyword is used to declare constants, which means that the variable cannot be reassigned. However, it does not mean that the value itself is immutable. In this code snippet, the variable hour is initially declared using const, but the value of hour is being updated in the subsequent lines of code based on conditions.

      The initial declaration with const only prevents reassignment of the variable hour, not the modification of the value itself. So, in the third line, hour is being reassigned a new value based on a conditional expression, which is allowed even though it was originally declared as a constant.

      In summary, while const prevents reassignment of variables, it does not make the value immutable. Therefore, the third line of the code snippet is valid and compiles without any issues 😁

      • James Larsen
        James LarsenMar 6, 2024

        Sorry, I am not Java Programmer and I didn't know the code was in Java. (I am a C, C+, C++, C# programmer) In those languages, Constants are constant! and not Immutable. Sorry for the confusion, but in my world constant means immutable, the exact opposite of variable! Thank you for the education!

        • Klecianny Melo
          Klecianny MeloMar 8, 2024

          Alright @jdlarsen1945, I thank you for your contribution to the article. Every discussion is valid, we can always learn something new together. I look forward to seeing you in the next posts so we can reflect on code or a career in technology! 😁

      • rcalvanese
        rcalvaneseMar 6, 2024

        Actually, I am pretty sure this will error. You cannot reassign a value to hour once it has been assigned the value of "07". "Uncaught SyntaxError: Identifier 'hour' has already been declared"

        • Klecianny Melo
          Klecianny MeloMar 8, 2024

          Hi @rcalvanese, how are you? How did you run the code? Was it with another string for the time in the constant "s"?

  • Michael Tharrington
    Michael TharringtonMar 4, 2024

    Yo! This is a really interesting and helpful post, Kleciann. Appreciate ya sharing! 🙌

    So, this isn't related to converting 12- to 24-hour time formats, but there's something I've been wondering in regards to coding time... do you know if there's anything special that needs to be done to account for leap year? I reckon once every four years the calendar needs to add in another day for February, but I wonder what the approaches for this are...

    • Klecianny Melo
      Klecianny MeloMar 4, 2024

      Hello @michaeltharrington, how are you? I studied the resolution to the time conversion problem only in this initial format. It's true, we have leap years like 2024, with 1 extra day in February. There must be an algorithm that takes this information into account. Thank you for your contribution! 😁

      • Michael Tharrington
        Michael TharringtonMar 4, 2024

        Heyo! Doing well, thankya. 😀

        No worries, totally understand that my question is kinda beyond the scope of this article. The two are connected because they are both about time, but def handled by different things. Anywho, really dig your article and thanks again for sharing with us. 🙌

        • Klecianny Melo
          Klecianny MeloMar 5, 2024

          It's true, your question complements my development because it relates to time. Thank you for the complement! 😁

    • Klecianny Melo
      Klecianny MeloMar 8, 2024

      Hello @michaeltharrington, how are you? Thinking about it, I think that whether the year is a leap year or not will not affect this hour conversion scenario. Because every 4 years we have 1 extra day in February, I believe it only affects the conversion of days. It makes sense? 🤔

      • Michael Tharrington
        Michael TharringtonMar 8, 2024

        That does make sense, Klecianny! Appreciate ya hitting me back. Sounds like it's mot so much a time problem (as in clock) but more of a date issue (calendars)... got it!

        • Klecianny Melo
          Klecianny MeloMar 8, 2024

          Sounds is great! I thank you for your contribution to the article @michaeltharrington! I was thinking about this issue these days and realized this point I mentioned. I look forward to seeing you in the next posts so we can reflect on code or a career in technology 😁

Add comment