JavaScript日期字符串转Epoch时间戳出现三位冗余的正确处理方式
问题:毫秒级Epoch时间戳转Date对象出错,求简洁规范的解决方法
我通过以下代码将日期字符串转换为Epoch时间戳:
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)
问题在于Date.parse返回的是毫秒级Epoch时间戳,使用setUTCSeconds传入该值时,得到了错误的年份55906(正确日期应为2023年12月9日)。我可以通过判断长度后除以1000处理,但有没有更简洁规范的正确方法?
解决方法
有两种简洁规范的处理方式:
- 直接用毫秒级时间戳实例化Date对象
Date构造函数本身支持直接传入毫秒级时间戳,无需先创建epoch时间再调用set方法:
var f = new Date(chartFrom); console.log(f); // 输出对应2023-12-09T00:00:00.000Z的本地时间
- 若坚持使用setUTCSeconds,先转成秒级时间戳
setUTCSeconds的参数是秒数而非毫秒数,只需将chartFrom除以1000转换单位即可:
var f = new Date(0); f.setUTCSeconds(chartFrom / 1000); console.log(f); // 同样得到正确日期
出错原因说明
Date.parse()返回的是从1970年1月1日00:00:00 UTC到目标日期的毫秒数,而setUTCSeconds()接收的参数是秒数。直接传入毫秒数相当于把时间跨度放大了1000倍,自然会得到远超预期的年份。
内容的提问来源于stack exchange,提问作者Matt Welander
相关产品推荐
相关产品推荐

