2010-02-04 44 views
3

我想採用時間戳(例如1263531246)並將其轉換爲適合輸出到符合xs:dateTime的屬性字段中的XML文件的字符串表示形式。 xs:dateTime預計類似:如何在Perl中以xs:dateTime格式打印日期時間?

2002-05-30T09:30:10-06:00

理想情況下,我會使用,其包括從UTC偏移量(如上)的形式輸出。在這個項目中,我受限於使用Perl。有什麼建議麼?

回答

5

這在Linux上工作:

$ perl -MPOSIX -e 'print POSIX::strftime("%Y-%m-%dT%H:%M:%S%z\n", localtime)' 
2010-02-04T17:37:43-0500

在Windows上,與ActiveState的Perl中,它打印:

2010-02-04T17:39:24Eastern Standard Time

使用DateTime

#!/usr/bin/perl 
use strict; use warnings; 

use DateTime; 
my $dt = DateTime->now(time_zone => 'EST'); 
print $dt->strftime('%Y-%m-%dT%H:%M:%S%z'), "\n" 

我得到的Windows正確的字符串以及:

E:\> t 
2010-02-04T18:06:24-0500

我相信Date::Format是重量輕得多模塊:

#!/usr/bin/perl 
use strict; use warnings; 

use Date::Format; 
print time2str('%Y-%m-%dT%H:%M:%S%z', time, 'EST'), "\n"; 

輸出:

E:\> t 
2010-02-04T18:11:36-0500
7

使用權DateTime格式化模塊,你可以無需編寫任何 格式的字符串和DateTime對象之間的轉換痛苦的正則表達式來解析或使用strftime()進行格式化。

您似乎需要XSD格式(ISO8601的子集,用於XML模式):請參閱DateTime::Format::XSD

use DateTime; 
use DateTime::Format::XSD; 

my $dt = DateTime->now; 
print DateTime::Format::XSD->format_datetime($dt); 

生產:

2010-02-04T23:24:11+00:00 

如果您需要處理大量的DateTime對象,你可以依靠自動格式化和字串縮短你的代碼;簡單的 '格式化' 參數傳遞給您的DateTime構造函數:

my $dt = DateTime->new(year => 1999, month => 1, day => 1, 
         formatter => 'DateTime::Format::XSD' 
        ); 

my $xml = "<date>$dt</date>"; # through the magic of overloading, this works! 

結果:

<date>1999-01-01T00:00:00+00:00</date> 

欲瞭解更多信息,請參閱http://search.cpan.org/dist/DateTime/lib/DateTime.pm#Formatters_And_Stringification