Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can I convert timezones in Perl?

Tags:

datetime

perl

gmt

I am trying to convert a date/time GMT 0 to GMT -6 in Perl.

For example, a DHCP Server lease time is in the following format:

2010/02/18 23:48:37

I am trying to convert that time to the Localtime zone (GMT -6) but need it to honor Daylight savings time.

The script below may be overkill, but I am not sure how to proceed from here. (Any suggestions would be awsome).

my $TIMESTART;

$TIMESTART = "2010/02/18 23:48:37";
$TIMESTART =~ s/\//-/g;

use DateTime;
use DateTime::TimeZone;

use DateTime::Format::MySQL;
my $dt = DateTime::Format::MySQL->parse_datetime($TIMESTART);

my $tz = DateTime::TimeZone->new( name => 'America/Chicago' );

print $tz->offset_for_datetime($dt) . "\n";

It will output the following lines:

2010-02-18T23:48:37
-21600

I need to be able to add -21600 to the date to get the local time zone of GMT -6 but I am not sure how to approch this.

like image 425
jinanwow Avatar asked Feb 24 '10 21:02

jinanwow


People also ask

How do I convert DateTime to timezone?

DateTime currentTime = TimeZoneInfo. ConvertTime(DateTime. Now, TimeZoneInfo. FindSystemTimeZoneById("Central Standard Time"));

How do I get GMT time in Perl?

The function gmtime() in Perl works just like localtime() function but the returned values are localized for the standard Greenwich time zone. When called in list context, $isdst, the last value returned by gmtime, is always 0. There is no Daylight Saving Time in GMT.

How do I change the date format in Perl?

You can use the POSIX function strftime() to format date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent.


1 Answers

Call set_time_zone method 2 times:

my $dt = DateTime::Format::MySQL->parse_datetime($TIMESTART);
$dt->set_time_zone('UTC'); ## set timezone of parsed date time
$dt->set_time_zone('America/Chicago'); ## change timezone in safe way

print DateTime::Format::MySQL->format_datetime($dt),"\n"; ## check the result

How it works:

  • when you create DateTime object without time zone specified, "floating" time zone is set
  • first call of set_time_zone change time zone to UTC without conversion
  • second call of set_time_zone change UTC to America/Chicago
like image 60
Ivan Nevostruev Avatar answered Oct 15 '22 11:10

Ivan Nevostruev