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?
it's okay, js (for example Date.now()
) brings 3 more symbols because of milliseconds dimension
to solve this use:
const jsUnixTime = 1223334444000; // not more than 13 length
const unixTime = (jsUnixTime / 1000) | 0;
console.log(unixTime, jsUnixTime);
So, your code:
const arrivalValue = '2023-12-09T14:03';
// const arrivalValue = $('#aircraft_arrival_time').val();
// 2023-12-09T14:03
console.log(arrivalValue);
const arrivalDatePart = arrivalValue.split('T')[0];
const arrivalDate = arrivalDatePart + 'T00:00:00.000Z';
// 2023-12-09T00:00:00.000Z
console.log(arrivalDate);
// beginning of that day, UTC
const chartFrom = (Date.parse(arrivalDate) / 1000) | 0;
// 1702080000000
console.log(chartFrom);
// The 0 there is the key, which sets the date to the epoch
const finalDate = new Date(0);
finalDate.setUTCSeconds(chartFrom);
console.log(finalDate);