我需要比较后端给的时间戳(在Perl中)和前端给的时间戳(在JS中),因此我需要确保它们都使用相同的时间单位。
对于JS来说,quoting很简单:
A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date.
对于Perl,有关
$dt->epoch()
的documentation表示:Return the UTC epoch value for the datetime object. Datetimes before the start of the epoch will be returned as a negative number.
The return value from this method is always an integer.
Since the epoch does not account for leap seconds, the epoch time for 1972-12-31T23:59:60 (UTC) is exactly the same as that for 1973-01-01T00:00:00.
对我来说,不清楚返回的整数是毫秒还是秒(在第二种情况下,我需要to convert JS epoch in seconds或反之亦然)。
哪一个是正确的?
最佳答案
在DateTime的上下文中,“epoch”是指Unix time,它是自1970-01-01T00:00:00Z以来没有leap秒的秒数。
$ perl -MDateTime -e'CORE::say DateTime->from_epoch( epoch => 1 )'
1970-01-01T00:00:01
$ perl -MDateTime -e'CORE::say DateTime->from_epoch( epoch => 1000 )'
1970-01-01T00:16:40
但是,DateTime支持分辨率为纳秒的时间,因此您可以使用以下代码获取JavaScript时间戳。
my $js_time = $dt->epoch * 1000 + $dt->millisecond;
当然,要获得毫秒分量的非零值,则假定创建了具有足够精确时间的DateTime对象。事实并非如此
my $dt = DateTime->now();
因为它使用
time
运算符来获取当前时间。要获得更高分辨率的时间戳,可以使用以下命令:use Time::HiRes qw( time );
my $dt = DateTime->from_epoch( epoch => time() );
关于javascript - Perl DateTime的纪元是毫秒还是秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52427646/