javascript 将日期字符串转换为纪元返回三位数字太多

问题描述 投票:0回答:1

我正在将字符串转换为纪元,如下所示:

    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)

问题在于它以毫秒为单位返回纪元,当通过类似 https://www.epochconverter.com/ 运行时,它将被识别为毫秒格式,并正确解释为 2023 年 12 月 9 日而不是年份55906 =)

我假设我可以检查chartFrom的长度,如果长度出乎意料地长,则除以1000,但是有没有一种干净的方法可以做到这一点?

javascript date utc epoch
1个回答
0
投票

没关系,js(例如

Date.now()
)因为毫秒维度,多带了3个符号

解决这个问题:

const jsUnixTime = 1223334444000; // not more than 13 length
const unixTime = (jsUnixTime / 1000) | 0;
console.log(unixTime, jsUnixTime);
© www.soinside.com 2019 - 2024. All rights reserved.