I am converting a string to epoch like this:
arrival = $('#aircraft_arrival_time').val();
console.log(arrival); //2023-12-09T14:03
temp = arrival.split("T");
arrivalDatePart = temp[0];
arrivalDate = arrivalDatePart + "T00:00:00.000Z";
console.log(arrivalDate); //2023-12-09T00:00:00.000Z
chartFrom = Date.parse(arrivalDate); //beginning of that day, UTC
console.log(chartFrom); //1702080000000
var f = new Date(0); // The 0 there is the key, which sets the date to the epoch
f.setUTCSeconds(chartFrom);
console.log(f); //Tue Oct 09 55906 02:00:00 GMT+0200 (centraleuropeisk sommartid)
The trouble is that it returns the epoch in milliseconds, and while running that through something like https://www.epochconverter.com/ it will be identified as millisecond format, and correctly interpreted as 9 December 2023 rather than the year 55906 =)
I assume I could check the length of chartFrom and divide by 1000 if the length is unexpectedly long, but is there a clean way to do it right?
2
Answers
it’s okay, js (for example
Date.now()
) brings 3 more symbols because of milliseconds dimensionto solve this use:
So, your code:
This function sets the seconds portion of the date to a number between 0 and 59 (values outside this range will correct the date). You’re providing UTC timestamp in milliseconds.
Change your code to one of the following:
A few other smaller improvements could be made to your code but I am concerned about you treating a date with unknown timezone to UTC. The date could correspond to Dec 8, 9 or 10 UTC depending on which timezone it represents.