2011-11-21 170 views
9

我試圖在perl中將字符串轉換爲日期,但得到錯誤。perl如何將字符串轉換爲Datetime?

use strict; 
use warnings; 
use DateTime; 
use Date::Manip; 

my $date = ParseDate("20111121"); 
print "today is ".$date->day_of_week."\n"; 

錯誤

Can't call method "day_of_week" without a package or object reference 

貌似包導入有問題...

感謝

回答

16

DateTime不分析日期。我會去爲Time::Piece核心模塊,讓您strptime():

#!/usr/bin/env perl 
use strict; 
use warnings; 
use Time::Piece; 
my $t = Time::Piece->strptime("20111121", "%Y%m%d"); 
print $t->strftime("%w\n"); 
+0

爲什麼當有核心模塊時,人們推薦使用DateTime進行簡單的perl日期操作? (我是perl的新手,這是一個genuin問題) – Relequestual

+0

@Relequestual'DateTime'提供計算日期持續時間(例如兩個日期之間的天數)等功能。也許它最重要的功能是它可以處理日曆而不是時間。因此,您可以計算「昨天」的值,而不考慮夏令時和不存在的時間。查看模塊文檔和[FAQ4](http://perldoc.perl.org/perlfaq4.html#How-do-I-find-yesterday%27s-date?) – JRFerguson

0

從模塊文檔:This module does not parse dates

您需要添加代碼,如I printed a date with strftime, how do I parse it again?中建議從a轉換字符串轉換爲日期時間對象。

+0

我改成這個,還是不行。使用DateTime; my $ dateStr ='20111121'; my $ year = substr($ dateStr,0,4); my $ month = substr($ dateStr,4,2); my $ day = substr($ dateStr,6,2); print $ year。 「/".$monmon."/".$day."\n」 my $ date = DateTime-> new( year => $ year, month => $ month, day => $ day, ); – user595234

+0

我發現原因。謝謝 – user595234

19

的DateTime本身沒有分析工具,但也有許多parsers是gererate datetime對象。大多數情況下,您可能需要DateTime::Format::Strptime

use DateTime::Format::Strptime qw(); 
my $format = DateTime::Format::Strptime->new(
    pattern => '%Y%m%d', 
    time_zone => 'local', 
    on_error => 'croak', 
); 
my $dt = $format->parse_datetime('20111121'); 

或者你可以自己動手做。

use DateTime qw(); 
my ($y,$m,$d) = '20111121' =~ /^([0-9]{4})([0-9]{2})([0-9]{2})\z/ 
    or die; 
my $dt = DateTime->new(
    year  => $y, 
    month  => $m, 
    day  => $d, 
    time_zone => 'local', 
);