Sarah
Sarah

Reputation: 9

Perl: How to convert a unix timestamp+timezone into local time

the basic question is in the header: I have a unix timestamp and a timezone, e.g. "America/Caracas" and I would like to convert it to the timezone's local time.

Searching through stackoverflow, I found someone else asking pretty much the same question, however, the provided answer code

$t = new DateTime();
$t->setTimestamp( $time=time() );
$t->setTimeZone(new DateTimeZone("America/Denver"));
print $t->format(DateTime::RFC850);

does not work (anymore?). DateTime() does not allow me to set a timestamp; i did look through the DateTime source, but also did not see, where i could hook up my own timestamp. Any thoughts/help?

Many thanks in advance!

Upvotes: 0

Views: 5224

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 150138

use DateTime;

my $dt = DateTime->from_epoch(
    epoch     => time(), 
    time_zone => "America/Denver"
);
print "$dt\n";

See the DateTime docs for details.

Upvotes: 4

marto
marto

Reputation: 4503

Try:

my $epoch = time;
warn $epoch;
my $dt = DateTime->from_epoch( epoch => $epoch );
warn $dt->year;
#and so on

Upvotes: -1

Related Questions