在Perl中,存在一个名为
timelocal
的函数,用于将时间转换为纪元.
例如:我的$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之间,它将自动转换为当前世纪的一年,如文档中所述;从1900年开始,100到999之间的年份被视为抵消.如果不破解来源,你就无法解决这个问题.
如果您的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位整数,过去或将来过多的日期将导致整数溢出.如果use64bitint = define出现在perl -V的输出中(带有大写’V’),则perl支持64位整数.