Search code examples
javascriptdatetimetimezoneutc

Get time difference (hours, seconds, minutes) between two different date strings in UTC


I need to keep track of how much time a user is doing a task. Thus I would like to get the exact time difference between the time when a user logged in and the current time. The time the user logged in comes from the data base.

*Something worth noting is that I need to work in UTC.

From the database it comes likes this and it´s already in UTC: 2020-05-12 18:04:25

This is what I was trying to do more or less:

let timer = Math.abs(Date.now() - new Date(timeFromDataBase).getTime());

let minutes = Math.floor(timer / 60000);
let seconds = ((timer % 60000) / 1000).toFixed(0);

Undoubtedly the amount of minutes and seconds need to increase BUT for some reason they keep decreasing for me (AND turning date.now() and the other variable around is NOT the solution)! I´ll attach a picture of my console logs (so you can see how the numbers go down, even though more time passes so they should go up):

enter image description here

I´m clearly missing something but I can´t see what. I think it might be that the Date.now() is giving me the miliseconds in my local time and I need them in UTC (if this was to be the case I still couldn´t find how to do it).


Solution

  • The problem is that your data from the database is not in the correct UTC format so the value is being interpreted as local time -- which is why you seeing negative values.

    When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

    So your value of 2020-05-12 18:04:25 ends up possibly being time in the future depending on where you are.

    You need to return UTC formatted string including the offset info from the db - either: (Z or +hh:mm or -hh:mm), or reconstruct that string on the client.

    Demo:

    const dbDate = new Date('2020-05-12 18:04:25');
    console.info(dbDate.toUTCString()); // future for me in US
    console.info(Date.now() - dbDate.getTime()); // negative value for me in US
    
    const utcDate = new Date('2020-05-12T18:04:25.000+00:00');
    console.info(utcDate.toUTCString());
    console.info(Date.now() - utcDate.getTime());
    
    const utcDateZ = new Date('2020-05-12T18:04:25.000z');
    console.info(utcDateZ.toUTCString());
    console.info(Date.now() - utcDateZ.getTime());