这是一个DateTime错误还是我错过了什么?
sub get_diff_same_day { # return only the time difference between 2 dates my ($dNow,$dt) = @_; my $dtx = $dt->clone(); $dtx->set_year( $dNow->year ); $dtx->set_month( $dNow->month ); $dtx->set_day( $dNow->day ); say $dNow; say $dtx; return $dtx->subtract_datetime_absolute($dNow); }
输出:
2012-04-18T09:56:39 2012-04-18T09:56:40 0 DateTime::Duration=HASH(0x1e10a34) 'days' => 0 'end_of_month' => 'wrap' 'minutes' => 0 'months' => 0 'nanoseconds' => 0 'seconds' => 3577 # <= huh?
但是,如果我使用的话,而不是subtract_datetime_absolute
$dtx - $dNow
这给了我:
0 DateTime::Duration=HASH(0x1bada04) 'days' => 0 'end_of_month' => 'wrap' 'minutes' => 0 'months' => 0 'nanoseconds' => 0 'seconds' => 1
在我看来,subtract_datetime_absolute没有考虑DateTime :: set_xxxx函数.
编辑:下面的示例.
use Modern::Perl; use autodie; use DateTime; use constant OFFSET => 0; ## main test(); sub test { my $Now = DateTime->Now( time_zone => 'local' )->add( hours => OFFSET ); my $ddt = get_rand_date(); my $secs = get_secs_same_day_broken ($Now,$ddt); my $secs2 = get_secs_same_day($Now,$ddt); if ( $secs != $secs2 ) { say "expecting same result ( $secs,$secs2 )"; } } sub get_secs_same_day_broken { # return the seconds time difference between 2 dates my ($dNow,$dt) = @_; my $dtx = $dt->clone(); $dtx->set_year( $dNow->year ); $dtx->set_month( $dNow->month ); $dtx->set_day( $dNow->day ); say "A: $dNow vs $dtx"; return $dtx->subtract_datetime_absolute($dNow)->seconds; } sub get_secs_same_day { # return the seconds time difference between 2 dates my ($dNow,$dt) = @_; my $dtx = $dt->clone(); $dtx->set_year( $dNow->year ); $dtx->set_month( $dNow->month ); $dtx->set_day( $dNow->day ); say "B: $dNow vs $dtx"; return ($dtx - $dNow)->seconds; } sub get_rand_date { my $d = int(rand(27)) + 1; my $M = int(rand(11)) + 1; my $h = int(rand(24)); my $m = int(rand(60)); my $s = int(rand(60)); my $dt = DateTime->new( day => $d,month => $M,year => 2012,hour => $h,minute => $m,second => $s ); $dt->add( hours => OFFSET ); return $dt; }
解决方法
$dtx-> subtract_datetime_absolute($Now) – > seconds返回两个日期之间的差值,作为绝对秒数.
试试这个:
my $Now = DateTime->Now(time_zone => 'local'); my $dtx = $Now->clone->set(hour => 22,minute => 22,second => 22); { use integer; my $seconds = $dtx->subtract_datetime_absolute($Now)->seconds; my $minutes = $seconds / 60; say $seconds - ($minutes * 60); } { my $seconds = ($dtx - $Now)->seconds; say $seconds; }