Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Convert LST dates to LT dates

by Anonymous Monk
on Dec 04, 2020 at 00:13 UTC ( #11124618=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have a list of dates in local standard time that I want to convert to local time.

I came up with this, but I guess there's some smarter way...

Thanks



use strict; use DateTime::Duration; use DateTime; # These are local standard times in Europe/Rome, i.e. always UTC+0100 my @dates = ( [2020,12,2,1,0], [2021,7,2,1,0] ); my $timezone = '+0100'; # This is the duration to be added to go from LST to UTC my $seconds = -($timezone/100) * 3600; my $dur = DateTime::Duration->new( years => 0, months => 0, weeks => 0, days => 0, hours => 0, minutes => 0, seconds => $seconds, nanoseconds => 0 ); for my $date (@dates) { my $dt = DateTime->new( year => => $date->[0], month => $date->[1], day => $date->[2], hour => $date->[3], minute => $date->[4], second => 0, nanosecond => 0, time_zone => 'UTC' ); $dt->add($dur); # This is a DateTime object in LST print "LST: ",join("-",@{$date}),"\n"; print "UTC: ",$dt->set_time_zone("UTC"),"\n"; print "LT: ",$dt->set_time_zone("Europe/Rome"),"\n"; }

Replies are listed 'Best First'.
Re: Convert LST dates to LT dates
by ikegami (Pope) on Dec 04, 2020 at 05:17 UTC

    Close! Instead of using UTC and adding an hour (which could have been done much more simply using $dt->add( hours => 1 )), use +0100 as the time zone.

    use DateTime qw( ); use DateTime::TimeZone qw( ); my $old_tz = DateTime::TimeZone->new( name => "+0100" ); my $new_tz = DateTime::TimeZone->new( name => "Europe/Rome" ); for my $date ( [ 2020, 12, 2, 1, 0 ], [ 2021, 7, 2, 1, 0 ], ) { my $dt = DateTime->new( year => => $date->[0], month => $date->[1], day => $date->[2], hour => $date->[3], minute => $date->[4], time_zone => $old_tz, ); say $dt->strftime("%FT%T%z"); $dt->set_time_zone($new_tz); say $dt->strftime("%FT%T%z"); }

    Output:

    2020-12-02T01:00:00+0100 ST 2020-12-02T01:00:00+0100 ST used in winter in Europe/Rome 2021-07-02T01:00:00+0100 ST 2021-07-02T02:00:00+0200 DT used in summer in Europe/Rome

    You can use the strings +0100 and Europe/Rome directly; I simply used DT::TZ objects for efficiency.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11124618]
Approved by GrandFather
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2021-01-25 16:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?