Humble Debugger
Humble Debugger

Reputation: 4605

How to get seconds of given timezone - UTC time in Perl

I have a file with lines of the form : 1311597859.567497 y_value_to_plot. The first token is time since epoch, i.e. unix time. The user wants to call plot_file.pl with this filename and a timezone specification such as "America/New_York" or "Europe/London". Calling gnuplot on this file with set xdata time; set timefmt "%s" works but it shows the hours in UTC time. But the user would like to see the local time. So for 1311597859.567497, without any timezone changes, gnuplot would show 12:44:19, but if the user specifies America/New_York, he would like to see 08:44:19 in the gnuplot window. I though a simple fix would be to calculate the offset between utc and the given timezone and subtract that from the token, and then run new plot on this new file. Hence I was looking for a way to get offset_seconds of UTC from a given timezone in Perl.

Upvotes: 2

Views: 2484

Answers (1)

justkt
justkt

Reputation: 14766

By unix time I assume you mean seconds since the epoch in local time and you are trying to convert to seconds since the epoch in UTC.

Consider using a module such as Time::Zone or DateTime::TimeZone (part of DateTime) to help with such a calculation.

For example with Time::Zone:

use Time::Zone;
my $offset_sec = tz_local_offset(); # or tz_offset($tz) if you have the TZ
                                    # in a variable and it is not local

my $time = time(); # realistically it will be the time value you provide in localtime
my $utc_time = $time + $offset_sec;

With DateTime and DateTime::TimeZone:

use DateTime;
use DateTime::TimeZone;

# cache local timezone because determining it can be slow
# if your timezone is user specified get it another way
our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' );
my $tz = DateTime::TimeZone->new( name => $App::LocalTZ );

my $dt = DateTime->now(); # again, time will be whatever you are passing in
                          # formulated as a DateTime
my $offset = $tz->offset_for_datetime($dt);

Note that using DateTime you can simply convert a DateTime object from local time to UTC time via set_time_zone('UTC') and then format it for gnuplot also.

To do it all by hand, you can format the output of gmtime if you can get to epoch seconds from your local time (perhaps using mktime out of a date/time string).

Upvotes: 4

Related Questions