perl有两个取得时间的函数:localtime和gmtime
两个函数的用法一样,区别在于localtime为取得本地时间, gmtime格林威治时间

通过Perl中提供的gmtime函数,你可以自己来验证这点。给定一个用以表示自从纪元以来的秒数的整数,通过gmtime函数可以计算出代表相应的日期和时刻,Perl中的time() 函数返回以纪元秒形式表示的当前日期和时间。如果你打算把它转换为字符串,就可使用gmtime() 和localtime() 函数:
而日常生活中的日期和时间是用字符串来表示的,你怎样才能把日常所用的日期和时间串格式转换成纪元秒呢?

方法之一是写出语法分析小程序,该方法灵活而快速:
use Time::Local;
@months&leftsign;qw(Jan Feb Mar Apr May Jun
Jul Aug Sep Oct Nov Dec)&rightsign; = (0..11);
$_ = "19 Dec 1997 15:30:02";
/(\\d\\d)\\s+(\\w+)\\s+(\\d+)\\s+(\\d+):(\\d+):(\\d+)/ or die "Not a date";
$mday = $1;
$mon= exists($months&leftsign;$2&rightsign;) ? $months&leftsign;$2&rightsign; : die "Bad month";
$year = $3 — 1900;
($h, $m, $s) = ($4, $5, $6);
$epoch_seconds = timelocal($s,$m,$h,$mday,$mon,$year);

一个更通用些的方法,是从CPAN(Perl综合网)中安装Date::Manip 模块。
use Date::Manip;
$epoch_seconds = UnixDate("19 Dec 199715:30:02","s");
注意,由于 Date::Manip是个大模块,使用该模块时,将会增加你的程序的启动时间。其中一个原因是 Date::Manip将对多种不同的格式进行识别

localtime EXPR
            Converts a time as returned by the time function to a 9-element
            list with the time analyzed for the local time zone. Typically
            used as follows:

use HTTP::Date ;
$tt=localtime();
$str=time2str($tt);
print $tt."\\n";

print $str."\\n";
$n= str2time($str);
$ee=100;
$n=$n+$ee;

$str2=time2str($n);
print $str2."\\n";
exit(0);

如果用TIME
[root@ www.yippeesoft.com cgi-bin]# date
Fri Nov  4 21:37:53 CST 2005
[root@ www.yippeesoft.com cgi-bin]# ./sftest.pl
1131111475
Fri, 04 Nov 2005 13:37:55 GMT
Fri, 04 Nov 2005 13:39:35 GMT

如果用LOCALTIME
[root@ www.yippeesoft.com cgi-bin]# ./sftest.pl
Fri Nov  4 21:38:16 2005
Thu, 01 Jan 1970 00:00:00 GMT
Thu, 01 Jan 1970 00:01:40 GMT
[root@ www.yippeesoft.com cgi-bin]#

use HTTP::Date ;
$tt=localtime();
#$str=time2str($tt);
print $tt."\\n";

#print $str."\\n";
$n= str2time($tt);
print $n."\\n";
$ee=100;
$n=$n+$ee;
$str2=time2str($n);
print $str2."\\n";
$ttt=str2time($str2);
print $ttt."\\n";
exit(0);

[root@ www.yippeesoft.com cgi-bin]# ./sftest.pl
Fri Nov  4 21:41:01 2005
1131111661
Fri, 04 Nov 2005 13:42:41 GMT
1131111761

比较古怪,我不能在PERL上面添加模块,所以使用了HTTP::Date,不过 LOCALTIME STR2TIME 得到的和 TIME() 取得的不一致,怪怪的

历史博文

标签:, , , , ,
十一月 15, 2005 at 9:45 上午 by yippee 1,320 次
Category: Dev
Tags: , , , , ,