Perl本地时间错误

时间:2012-03-02 14:11:18

标签: perl time mktime localtime

我在2009年2月28日 th 获得了纪元时间,  然后添加一周的秒数。 但后来我得到3月4日 th 而不是3月7日 th 。为什么呢?

以下是代码:

#!/usr/bin/perl
use POSIX;

my $hours_per_day    =   24;
my $hours_per_week   =  168;
my $seconds_per_hour = 3600;
my $seconds_per_week = ($hours_per_week * $seconds_per_hour);

#begin at my first week
$epoch_seconds = POSIX::mktime(0,0,12,28,2,109);

for(my $cline = 1; $cline <= 250; $cline++) {
    ($sec,$min,$hour,$mday,$month,
     $year,$wday,$yday,$isdst) = localtime($epoch_seconds);

    $year += 1900;
    print STDOUT "$cline <=> $year/$month/$mday\n";

    $epoch_seconds += $seconds_per_week;
}

2 个答案:

答案 0 :(得分:5)

你将从2009年3月28日开始,一周后是4月。 4,2009。

use POSIX;

my $hours_per_day=24;
my $hours_per_week=168;
my $seconds_per_hour=3600;
my $seconds_per_week=($hours_per_week*$seconds_per_hour);

#begin at my first week
my $epoch_seconds=POSIX::mktime(0,0,12,28,2,109);

for(my $cline=1; $cline<=250; $cline++) {
    my ($sec,$min,$hour,$mday,$month,
     $year,$wday,$yday,$isdst) =localtime($epoch_seconds);

    print strftime( "%A, %B %e, %Y\t", localtime($epoch_seconds) );
    $year+=1900;
    print STDOUT "$cline <=> $year/$month/$mday\n";

    $epoch_seconds+=$seconds_per_week;
}

PS:您真的应该使用strftime格式化日期。请参阅perldoc POSIX并搜索/ strftime /.

答案 1 :(得分:2)

并非每个星期都是$ seconds_per_week long(闰年等),你应该使用一个函数/库/模块为你做计算。

与解释herehere一样。祝你好运!

相关问题