slayedbylucifer slayedbylucifer -4 years ago 140
Perl Question

perl "DateTime" module print wrong time

I am using DateTime module. however it is providing wrong time. Please consider below code:

#!/usr/bin/perl -w
use strict;

use Time::localtime;
my $now = ctime();
print $now."\n";

print "------------------------------\n";

use DateTime;
my $dt = DateTime->now;
print $dt."\n";


And its output is:

Wed Dec 26 22:11:52 2012
------------------------------
2012-12-27T06:11:52


so, As you can see, the
DateTime
output is leading by 8 hours which is wrong. Here is the Linux
date
command output:

# date
Wed Dec 26 22:13:17 PST 2012


So, the
date
command output matches with that of
time::localtime
output.

could you help me understand where I am going wrong in using
DateTime
module.

-Thanks.

UPDATE:

from hte CPAN documentation:

DateTime->now( ... )

This class method is equivalent to calling from_epoch() with the value returned from Perl's time() function. Just as with the new() method, it accepts "time_zone" and "locale" parameters.

By default, the returned object will be in the UTC time zone.


So, It seems that the time returned is in UTC. However, the timezone I am in in PST. Probably thats why I see the different time.

Answer Source

I passed the zone info and it works perfectly now:

#!/usr/bin/perl -w
use strict;

use Time::localtime;
my $now = ctime();
print $now."\n";

print "------------------------------\n";

use DateTime;
my $dt = DateTime->now ( time_zone => 'America/Los_Angeles' );
print $dt."\n";

Output:

Wed Dec 26 22:28:44 2012
------------------------------
2012-12-26T22:28:44

For East Coast

my $dateF = DateTime->now( time_zone => 'America/New_York' )->ymd;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download