Perl时间处理函数用法介绍

2019-10-01 09:43:19王振洲

如果调用localtime()或gmtime()时不带参数,它将自己调用time()

$now=localtime();
($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst)=localtime();

二. Perl时间处理函数中(日期和时间操作)

1. 计算两个时刻之间的时间段,
只需将它们转换为相应的纪元秒,然后两数相减即可:
$difference_in_seconds=$later_datetime-$earlier_datetime;

要把秒转换为分,时,或天数,只须要分别将它们除以60,3600和86400即可:

$difference_in_minutes=$difference_in_seconds/60;
$difference_in_hours=$difference_in_seconds/3600;
$difference_in_day=$difference_in_seconds/86400;

2. 计算"4天后是几号?":

$then=time()+86400*4;
print scalar(localtime($then));

它给出的答案精确到秒。
例如,
如果4天后的纪元秒值为932836935,你可以输出日期的字符串如下;
Sat Jul 24 11:23:17 1999

3. 输出某个日期的午夜时分
如"Sat Jul 24 00:00:00 1999",
运用如下模块:
$then=$then-$then%86400;#去掉那个日期的尾巴

类似地,你可以用四舍五入法,输出最靠近午夜时分的日期:

$then += 43200; #add on half a day
$then = $then - $then%86400; #truncate to the day

如果你的时区距离GMT为相差偶数个小时,这就管用了。
并不是所有的时区都是很容易处理的。
你所真实须要的是在你自己的时区内计算纪元秒,而不是在GMT中计算。

Perl中的名为Time::Local的模块,
可以提供两个函数timelocal()和timegm()。其返回值同localtime()和gmtime()一样。

use Time::Local;
$then = time() + 4*86400;
$then = timegm(localtime($then)); #local epoch seconds
$then -= $then%86400; #truncate to the day
$then = timelocal(gmtime($then)); #back to gmt epoch seconds
print scalar(localtime$then,“n”。

三. Perl时间处理函数中日常生活所用的日期和时间的表示

前面介绍了时,分,年等值的意思,也了解了纪元秒的意思。
而日常生活中的日期和时间是用字符串来表示的,
怎样才能把日常所用的日期和时间串格式转换成纪元秒呢?

1. 要领之一是写出语法分析小程序,该要领灵活而高速:

#!/usr/bin/perl

use Time::Local;
@months{qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)}=(0..11);
$_ = "19 Dec 1997 15:30:02";
/(dd)s+(w+)s+(d+)s+(d+):(d+):(d+)/ or die "Notadate";


$mday=$1;
$mon=exists($months{$2})?$months{$2}:die"Badmonth";
$year=$3-1900;
($h,$m,$s)=($4,$5,$6);
$epoch_seconds = timelocal($s,$m,$h,$mday,$mon,$year);


print "day: ",$mday,"n";
print "mon: ",$mon,"n";
print "year: ",$year,"n";
print "seconds: ",$epoch_seconds,"n";

2. 一个更通用些的要领,是从CPAN安装Date::Manip模块。