2013-01-03 43 views
3

我有一個perl腳本獲取當前時間,但我也希望在當前時間之前45天獲得日期。以下是我有:Perl過去日期如何?

*使用日期::計算DHMS這就是爲什麼第二格式化的方式是已經嘗試過,但它一直返回一個錯誤

# get the current time stamp 
use POSIX qw(strftime); 
my $current_time = strftime("%Y-%m-%d %H:%M:%S", localtime); 

print "\n$current_time\n"; 

# get the date 45 days ago 
my $time = strftime("%Y, %m, %d, %H, %M, %S", localtime); 

print "\n$time\n\n"; 
+1

「不斷返回錯誤」:告訴你在做什麼,有什麼錯誤它給 – ysth

+0

月分離之後,日期和年份分解爲單獨的變量Date :: Calc方法成功。 –

回答

5

最好使用日期時間,DateManip,或Date :: Calc,而且你還可以:

use POSIX 'strftime', 'mktime'; 

my ($second,$minute,$hour,$day,$month,$year) = localtime(); 
my $time_45_days_ago = mktime($second,$minute,$hour,$day-45,$month,$year); 
print strftime("%Y-%m-%d %H:%M:%S", localtime $time_45_days_ago), "\n"; 
+0

在我看來,這個解決方案很難閱讀,特別是對於那些進行維護的人。我寧願DateTime的減法。但是,如果沒有DateTime模塊可用... – fanlim

5

你試過DateTime

my $now = DateTime->now(time_zone => 'local'); 
my $a_while_ago = DateTime->now(time_zone => 'local')->subtract(days => 45); 
print $a_while_ago->strftime("%Y, %m, %d, %H, %M, %S\n"); 
+0

不幸的是,對於這個腳本,DateTime不可用。猜猜我應該在原始問題中聲明這一點。 –

2

下面是使用DateTime一個簡單的解決方案:

use strict; 
use warnings; 
use DateTime; 

my $forty_five_days_ago = DateTime->now(time_zone=>"local")->subtract(days => 45); 

my $output = $forty_five_days_ago->ymd(", "); 

$output .= ", " . $forty_five_days_ago->hms(", "); 

print "$output\n"; 
+2

'$ output = $ forty_five_days_ago-> strftime(「%Y,%m,%d,%H,%M,%S」);'也可以這樣做。 – ikegami

3
use DateTime; 

my $now = DateTime->now(time_zone=>'local'); 
my $then = $now->subtract(days => 45); 
print $then->strftime("%Y, %m, %d, %H, %M, %S"); 

設置TIME_ZONE,重要的是在這裏。