在 Perl 中,有一个名为 timelocal
的函数。存在将时间转换为纪元。
示例: my $epoch = timelocal($sec, $min, $hour, $mday, $mon, $year)
然而,在处理非常远的过去(999 年之前)的时间时,此函数似乎存在固有缺陷 - 请参阅关于 Year Value Interpretation 的部分.更糟糕的是,它处理 2 位数年份的方式使事情变得更加复杂......
给定 999 年之前的时间,我如何才能准确地将其转换为相应的纪元值?
最佳答案
Given a time before the year 999 how can I accurately convert it to its corresponding epoch value?
您不能使用 Time::Local。
timegm
(由 timelocal
使用)contains以下:if ( $year >= 1000 ) {
$year -= 1900;
}
elsif ( $year < 100 and $year >= 0 ) {
$year += ( $year > $Breakpoint ) ? $Century : $NextCentury;
}
如果年份介于 0 到 100 之间,则会按照文档中的说明自动转换为当前世纪的年份; 100 到 999 之间的年份被视为从 1900 年开始的偏移量。如果不破解源代码,就无法解决这个问题。
如果您的 perl 被编译为使用 64 位整数*,您可以使用 DateTime模块代替:
use strict;
use warnings 'all';
use 5.010;
use DateTime;
my $dt = DateTime->new(
year => 1,
month => 1,
day => 1,
hour => 0,
minute => 0,
second => 0,
time_zone => 'UTC'
);
say $dt->epoch;
输出:
-62135596800
请注意,公历直到 1582 年才被采用,因此 DateTime 通过简单地从 1582 年向后扩展来使用所谓的“预测公历”。
* 对于 32 位整数,过去或 future 的日期太远会导致整数溢出。如果
use64bitint=define
,你的 perl 支持 64 位整数。出现在 perl -V
的输出中(大写“V”)。
关于perl - 将 999 年之前的时间转换为纪元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36165048/