Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the timezone of a datetime value in Perl?

Using this function:

perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'

It will return an epochtime - but only in GMT - if i want the result in GMT+1 (which is the systems localtime(TZ)), what do i need to change?

Thanks in advance,

Anders

like image 418
Anders Avatar asked Feb 01 '10 14:02

Anders


3 Answers

use DateTime;
my $dt   = DateTime->now;
$dt->set_time_zone( 'Europe/Madrid' );
like image 102
jacktrade Avatar answered Sep 20 '22 02:09

jacktrade


There is only one standard definition for epochtime, based on UTC, and not different epochtimes for different timezones.

If you want to find the offset between gmtime and localtime, use

use Time::Local;
@t = localtime(time);
$gmt_offset_in_seconds = timegm(@t) - timelocal(@t);
like image 30
mob Avatar answered Sep 20 '22 02:09

mob


While Time::Local is a reasonable solution, you may be better off using the more modern DateTime object oriented module. Here's an example:

use strict;
use DateTime;
my $dt = DateTime->now;
print $dt->epoch, "\n";

For the timezones, you can use the DateTime::TimeZone module.

use strict;
use DateTime;
use DateTime::TimeZone;

my $dt = DateTime->now;
my $tz = DateTime::TimeZone->new(name => "local");

$dt->add(seconds => $tz->offset_for_datetime($dt));

print $dt->epoch, "\n";

CPAN Links:

DateTime

like image 21
Kaoru Avatar answered Sep 20 '22 02:09

Kaoru