Вопрос

I get the epoch time at February 28th 2009, then add to it the number of seconds in a week. But then I get March 4th instead of March 7th. Why?

The following is the code:

#!/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;
}
Это было полезно?

Решение

You are starting with Mar. 28, 2009 and a week later is Apr. 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: You really should use strftime to format your dates. See perldoc POSIX and search for /strftime/.

Другие советы

Not every week is exactly $seconds_per_week long (Leap years etc), you should use a function/library/module that does the calculations for you.

Like explained here or here. Good luck!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top