2012-04-18 68 views
4

這是一個DateTime錯誤還是我錯過了什麼?Perl DateTime subtract_datetime_absolute有趣的行爲

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; 
} 
+2

請提供一些可運行。我討厭花費時間試圖讓這個和運行,只是爲了不能重現它。然後我不知道是不是因爲你做錯了什麼,或者是因爲它是你正在使用的模塊版本中的錯誤。用示例程序更新了 – ikegami 2012-04-18 09:39:26

+1

。 – Richard 2012-04-18 10:47:10

回答

3

$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; 
} 
+1

瞭解並感謝。 – Richard 2012-04-18 12:50:15