Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the timezone for Perl's localtime()?

Tags:

perl

In Perl, I'd like to look up the localtime in a specific timezone. I had been using this technique:

$ENV{TZ} = 'America/Los_Angeles';
my $now = scalar localtime;
print "It is now $now\n";
# WORKS: prints the current time in LA

However, this is not reliable -- notably, if I prepend another localtime() call before setting $ENV{TZ}, it breaks:

localtime();
$ENV{TZ} = 'America/Los_Angeles';
my $now = scalar localtime;
print "It is now $now\n";
# FAILS: prints the current time for here instead of LA

Is there a better way to do this?

like image 287
mike Avatar asked Apr 15 '09 19:04

mike


People also ask

What is Perl Localtime ()?

Description. This function converts the time specified by EXPR in a list context, returning a nine-element array with the time analyzed for the current local time zone. The elements of the array are − # 0 1 2 3 4 5 6 7 8 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

How do I get yesterday's date in Perl?

use DateTime qw( ); my $yday_date = DateTime ->now( time_zone => 'local' ) ->set_time_zone('floating') ->truncate( to => 'day' ) ->subtract( days => 1 ) ->strftime('%Y-%m-%d');


1 Answers

Use POSIX::tzset.

use POSIX qw(tzset);

my $was = localtime;
print "It was      $was\n";

$ENV{TZ} = 'America/Los_Angeles';

$was = localtime;
print "It is still $was\n";

tzset;

my $now = localtime;
print "It is now   $now\n";
$ perl -v

This is perl, v5.8.8 built for x86_64-linux-thread-multi

Copyright 1987-2006, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

$ perl tzset-test.pl
It was      Wed Apr 15 15:58:10 2009
It is still Wed Apr 15 15:58:10 2009
It is now   Wed Apr 15 12:58:10 2009
like image 83
ephemient Avatar answered Oct 18 '22 20:10

ephemient