SetJmp SetJmp - 1 year ago 120
Perl Question

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

expects something like:


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?

Answer Source

This works on Linux:

$ perl -MPOSIX -e 'print POSIX::strftime("%Y-%m-%dT%H:%M:%S%z\n", localtime)'

On Windows, with ActiveState Perl, it prints:

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

Using DateTime:

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

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

use strict; use warnings;

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


E:\> t
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download