2012-10-18 79 views
0

我有一個任務在perl中,我需要執行'some_code',但只有當日期比從現在開始計算的24小時早。我正在嘗試下面的代碼,但它似乎並沒有工作。perl日期操作

sub function { 

    use Date::Manip::Date 
    use Date::Parse 
    use Date::Format; 

    my $yesterday = time() - 60*60*24; 
    my $x = shift; 
    my $env = shift; 

    $env->{some_code} = 1 if $x < $yesterday; 

return $x; 
} 
+3

請提供例如'$ x'值,實際輸出與預期輸出。 – January

+2

'使用這些模塊是不夠的,這些模塊提供了必須應用於執行日期計算的功能。 –

+1

'$ x'有什麼樣的值?在你打電話之前,你從哪裏得到他們?他們是Unix時間值(1970年以來的秒數),就像'time()'的返回值嗎? – gpvos

回答

1

你可以很容易地做到這一點,只使用核心功能。

#!/usr/bin/perl                     

use strict; 

my $new_time = 1350570164; # 2012-10-18 14:22:44 
my $older_time = 1350450164; # 2012-10-17 05:02:44 

printf "time in sec: %d older that 24 hours: %d\n", $new_time, is_time_older_24($new_time); 
printf "time in sec: %d older than 24 hours: %d\n", $older_time, is_time_older_24($older_time); 

sub is_time_older_24 { 
    my $given_time = shift; 

    my $yesterday_time = time() - 60 * 60 * 24; 
    return $given_time <= $yesterday_time 
      ? 1 
      : 0; 
} 

輸出:

time in sec: 1350570164 older that 24 hours: 0 
time in sec: 1350450164 older than 24 hours: 1 
+1

這一般起作用,但不是確切的。使用日期/時間模塊可以解決諸如閏秒等問題。如果「close」足夠好,那麼這很好,如果您需要精確度,請使用模塊。 –

+0

@Joel Berger,這也是我的第一個想法,但規格要求24小時,而不是一天。 – ikegami

+0

@ikegami在任務危急的情況下我認爲我寧願相信這個模塊,然而,是的,24小時通常比一天更容易。 –

1
#! /usr/bin/env perl 
use Modern::Perl; 
use Data::Dumper; 
use DateTime; 

my $now = DateTime->new( 
        year => 2012, month => 10, day => 18, 
        hour => 17, minute => 30, 
        time_zone => 'UTC' 
       ); 
# my $now = DateTime->now(time_zone => 'UTC'); 

my $last_run = DateTime->new(
        year => 2012, month => 10, day => 17, 
        hour => 19, minute => 30, 
        time_zone => 'UTC' 
       ); 

my $duration= $now->subtract_datetime($last_run); 
say "hours: " . $duration->hours; 

結果:

hours: 22 

還看到: