开发者

How can I print a datetime in the xs:dateTime format in Perl?

I would like to take a time stamp (e.g. 1263531246) and convert it to a string representation suitable for output to an XML file in an attribute field conforming to xs:dateTime. xs:dateT开发者_开发问答ime expects something like:

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

Ideally, I would use the form of output that includes offset from UTC (as above). In this project, I am constrained to use Perl. Any suggestions?


Using the right DateTime formatting module, you can translate between formatted strings and DateTime objects without writing any painful regexes to parse or using strftime() to format.

You seem to need the XSD format (a subset of ISO8601, used in XML schemas): see DateTime::Format::XSD.

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

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

produces:

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

If you are processing lots of DateTime objects, you could shorten your code by relying on automatic formatting and stringification; simply pass the 'formatter' argument to your DateTime constructor:

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!

results in:

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

For more information, see http://search.cpan.org/dist/DateTime/lib/DateTime.pm#Formatters_And_Stringification.


This works on Linux:

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

On Windows, with ActiveState Perl, it prints:

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

Using 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"

I get the correct string on Windows as well:

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

I believe Date::Format is much lighter weight module:

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

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

Output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜