Home > Back-end >  Javascript Dates working weird (when converting milliseconds to seconds )
Javascript Dates working weird (when converting milliseconds to seconds )

Time:04-01

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.

Any help will be appreciated so much.

CodePudding user response:

I want to check if you know that date formats like "0000-00-00T00:00:00.000Z" are always recognized as universal time (UK time).

Try using 00:00 instead of the last Z character.

For example, if you are in the US East, it would be "2022-04-01T17:41:47.000-05:00".

CodePudding user response:

You should add the system timezone, like this:

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

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

  • Related