javascriptdatedatetimemillisecondsseconds

Javascript Dates working weird (when converting milliseconds to seconds )


I have future date and now date. Both of this dates are always in same day but with just different hours. My goal is to get the difference of seconds between the future date and now date as my countdown value for a timer. The problem is when I calculate I'm getting inaccurate results.

In my research formula of converting milliseconds to seconds is millis / 1000.0 but non of this returns accurate countdown result;

My code

let now = (new Date().getTime() / 1000.0);
let futureDate = (new Date('2022-04-01T17:41:47.000Z').getTime() / 1000.0);

let difference;
difference = (futureDate - now); // not accurate
difference = parseInt(difference, 10); // not accurate

I would like the solution to work normal on all timezones and to inherit local system timezone instead of future date timezone.

Any help will be appreciated so much.


Solution

  • You should add the system timezone, like this:

    let date = new Date('2022-04-01T17:41:47.000Z');
    let now = new Date().getTime() / 1000.0;
    let futureDate = (date.getTime() + date.getTimezoneOffset() * 60000) / 1000.0;
    
    let difference;
    difference = (futureDate - now); // not accurate
    difference = parseInt(difference, 10); // not accurate
    console.log(difference);