Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Date API is changing date when creating a new instance of Date object with parameter in milliseconds

I’m trying to parse epoch time in milliseconds to UTC timestamp. To achieve this I’m doing:

new Date([my variable in milliseconds]).toUTCString()

and this is returning the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

output

When the correct date should actually be:

correct date

To recreate this you can use this code:

let dateInMills = 1655154491.8357913;
let parsedDate = new Date(1655154491.8357913).toUTCString();

console.log(parsedDate);

The number that I’m passing to the Date object is the exact same number that is being passed during the tests as it is static data.

More proof on the error:

running the code in the browser console

>Solution :

The Date constructor can take a number as it’s parameter. However, this number should be in milliseconds. In your case, you seams to have the time in second. You should multiply your input by 1000.

let dateInMills = 1655154491.8357913;
let parsedDate = new Date(dateInMills * 1000).toUTCString();

console.log(parsedDate);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading