我想采用时间戳(例如1263531246)并将其转换为适合输出到符合的属性字段中的XML文件的字符串表示xs:dateTime.xs:dateTime期待类似的东西:
2002-05-30T09:30:10-06:00
理想情况下,我会使用包含UTC偏移量的输出形式(如上所述).在这个项目中,我被限制使用Perl.有什么建议?
使用正确的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);
Run Code Online (Sandbox Code Playgroud)
生产:
2010-02-04T23:24:11+00:00
Run Code Online (Sandbox Code Playgroud)
如果要处理大量DateTime对象,则可以依靠自动格式化和字符串化来缩短代码.只需将'formatter'参数传递给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!
Run Code Online (Sandbox Code Playgroud)
结果是:
<date>1999-01-01T00:00:00+00:00</date>
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅http://search.cpan.org/dist/DateTime/lib/DateTime.pm#Formatters_And_Stringification.
这适用于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"
Run Code Online (Sandbox Code Playgroud)
我在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";
Run Code Online (Sandbox Code Playgroud)
输出:
E:\> t 2010-02-04T18:11:36-0500
| 归档时间: |
|
| 查看次数: |
3226 次 |
| 最近记录: |