DEV Community

loading...

Handling time in JavaScript

matthewpalmer9 profile image Matthew Palmer ・2 min read

Depending on the project you are building, time can be a very important skill to master. This reality hit me when I went head first in a challenge on Edabit.com

Here is the general problem it needed me to solve:

function hoursPassed(t1, t2) {
    // `t2 - t1` must return the amount of hours passed
    // It must also return `There is no time passed.` 
    // if t2 is equal to t1
}
Enter fullscreen mode Exit fullscreen mode

Time is tricky since 1 hour behind 12:00 AM isn't 11:00 AM.
Naturally, we want our algorithm to reflect the laws of time. Wouldn't it be nice if this worked?

function hoursPassed(t1, t2) {
     return t2 - t1
}
Enter fullscreen mode Exit fullscreen mode

Unfortunately, this doesn't work for us. Time does come in different forms, however. Does military time ring a bell? Anything over 12:00 PM just adds to the hour. So 1:00 PM is really 13:00. That logic is handled below, assuming we pass the time of day in as an argument.

const hour = time =>
    time === "12:00 AM" ? 0 : +time.split(":")[0] + 12 * time.includes("P")
Enter fullscreen mode Exit fullscreen mode

Above, we are passing our time in as an argument. If it is midnight, the hour should be 0 out of 24 in a day. Otherwise, we are grabbing the parsed hour and only adding 12 to it if it is in the PM and not the AM. With booleans, true is equal to 1 while false is equal to 0. As far as numerical values go, this is a major convenience for us.

In PEMDAS (throwback to our younger days, no?), multiplication happens before addition. Our 12 is multiplied by either 0 or 1 depending on morning or afternoon time.

// Example outputs

hour("2:00 PM") // -> 14
hour("11:00 PM") // -> 23
hour("3:00 AM") // -> 3
hour("6:00 AM") // -> 6
Enter fullscreen mode Exit fullscreen mode

Fantastic! We have successfully created a function that converts our time into military time.

Now, we can use this function to our advantage:

function hoursPassed(t1, t2) {
    const h = hour(t2) - hour(t1);
    return h ? `${h} hours passed.` : "No time has passed"
}
Enter fullscreen mode Exit fullscreen mode

Within our function, we have set a constant variable of h equal to the hour difference. If h is equal to 0, then our ternary knows to return "No time has passed.". Remember that 0 equals false and 1+ equals true. Anything greater than 0 will ultimately be our hours passed.

I hope this algorithm helps many devs out there! This is bound to be in someone's technical interview. :)

Discussion (1)

Forem Open with the Forem app