How to change timezone for datetime value in Perl?

With this function:

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

It will return the epoch-making time - but only in GMT - if I want to get the result in GMT + 1 (which is the local time of the system (TZ)), what should I change?

Thanks in advance,

Anders

+7
timezone perl solaris epoch
source share
6 answers

There is only one standard definition for epoch time based on UTC, and not different eras for different time zones.

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); 
+4
source share
 use DateTime; my $dt = DateTime->now; $dt->set_time_zone( 'Europe/Madrid' ); 
+7
source share

While Time :: Local is a smart solution, you might be better off using a more modern, object-oriented DateTime module. Here is an example:

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

For time zones, 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

+3
source share

You just need to set the time zone. Try:

  env TZ = UTC + 1 perl -e 'use Time :: Local;  print timelocal ("00", "00", "00", "01", "01", "2000"), "\ n"; '
+2
source share

Time::Local::timelocal is the inverse of localtime . The result will be in the local time of your host:

  $ perl -MTime :: Local -le \
     'print scalar localtime timelocal "00", "00", "00", "01", "01", "2000"'
 Tue Feb 1 00:00:00 2000 

Do you want gmtime match this localtime ?

  $ perl -MTime :: Local '-le \
     'print scalar gmtime timelocal "00", "00", "00", "01", "01", "2000"'
 Mon Jan 31 23:00:00 2000 

Do you want it to be the other way around, localtime , which matches this gmtime ?

  $ perl -MTime :: Local -le \
     'print scalar localtime timegm "00", "00", "00", "01", "01", "2000"'
 Tue Feb 1 01:00:00 2000 
+2
source share

Another example based on DateTime :: Format :: Strptime

 use strict; use warnings; use v5.10; use DateTime::Format::Strptime; my $s = "2016-12-22T06:16:29.798Z"; my $p = DateTime::Format::Strptime->new( pattern => "%Y-%m-%dT%T.%NZ", time_zone => "UTC" ); my $dt = $p->parse_datetime($s); $dt->set_time_zone("Europe/Berlin"); say join ' ', $dt->ymd, $dt->hms; # shows 2016-12-22 07:16:29 
0
source share

All Articles