好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Perl时间处理函数使用详解

本文重点讨论Perl时间处理函数的概念,Perl能在绝大多数操作系统运行,可以方便地向不同操作系统迁移,并且Perl借取了C、sed、awk、shellscripting以及很多其他程序语言的特性

#!/usr/bin/perl
use Time::localtime;

$t_num = 96163200;
$tm = scalar(gmtime($t_num));
print $tm,"\n"; 
@months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
$month = @months[(gmtime($t_num))[4]];
print "MONTH: ",$month,"\n"; 
$now=localtime(time());
($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst)=localtime(time()); 
$now=localtime();
($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst)=localtime(); 
$difference_in_minutes=$difference_in_seconds/60;
$difference_in_hours=$difference_in_seconds/3600;
$difference_in_day=$difference_in_seconds/86400; 
$then=time()+86400*4;
print scalar(localtime($then)); 
$then += 43200; #add on half a day
$then = $then - $then%86400; #truncate to the day 
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”。 
#!/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";
/(\d\d)\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"; 
useDate::Manip;
$epoch_seconds=UnixDate("19 Dec 1997 15:30:02","s"); 
print 2**31-1,"\n";
2147483647 
print scalar(gmtime(2**31-1)),"\n";
Tue Jan 19 03:14:07 2038 
print scalar(gmtime(2**31)),"\n";
Fri Dec 13 20:45:52 1901 

对于32位有符号整数来说,2**31太大了。
它"翻卷过去了",其符号位被置为负号,因而成为了所能表示的最大负数。
这对应于1970年开始时刻之前的秒的最大值。
其结果说明了什么呢?你不能存储gmtime(2**31)之前或gmtime(2**31-1)之后的以纪元秒表示的日期。
你可千万不要想不开,这可不是什么大疑问。
如果你要用到32位有符号整数表示的纪元秒以外的时间,你只须要改动你的表示方式,
你可从CPAN中找到不少日期模块,其中的Date::Calc和Date::Manip很可能是功能最强的两个模块。
这两个模块运用自己的日期表示方式,以防止Y1901-Y2038的限定。
Date::Manip运用罗马历法,从公元0000到公元9999。
Date::Calc也运用罗马历法,可表示的年份从1到32767。

总结

Perl时间处理函数中对于在1902-2037范围内的日期和时期表示,把它们转换为纪元秒,
要存取这些数,你只需运用整数算术运算,gmtime()和localtime()函数,以及标准的Time::Local模块。
如果要对该范围以外的日期执行计算或者要分析某特殊的日期格式,
你可以运用CPAN中的Date::Manip和Date::Calc模块。

以上就是Perl时间处理函数使用详解的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于Perl时间处理函数使用详解的详细内容...

  阅读:49次