Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^3: DateTime Invalid local time for date in time zone

by mr_ron (Chaplain)
on Jul 11, 2018 at 17:48 UTC ( #1218337=note: print w/replies, xml ) Need Help??


in reply to Re^2: DateTime Invalid local time for date in time zone
in thread DateTime Invalid local time for date in time zone

Thank you for getting back on my question.

So, as documented in the "Invalid Local Times" and "Error Handling" sections, DateTime was throwing an exception by "die"ing with a string explaining the problem. haukex solution would do something very similar on $dt->set_time_zone('America/Los_Angeles'); if it didn't add an hour before setting the time zone. If it is possible that there may be other invalid timestamps based on DST then you can also catch the exception, try to verify that the problem is DST and handle the error accordingly. I am presenting, below, an exception handling solution based on your OP but you might want to similarly adjust the haukex solution.

#!/usr/bin/env perl use strict; use warnings; use DateTime; use Try::Tiny; my $occuranceTime = "00:02:00"; my $occuranceDate = "03/13/2016"; my ($recordSec, $recordHour, $recordMin) = split ':', $occuranceTime; my ($recordMonth, $recordDate, $recordYear) = split '/', $occuranceDat +e; my $recordOnPST = try { DateTime->new( year => $recordYear, month => $recordMonth, day => $recordDate +, hour => $recordHour, minute => $recordMin, second => $recordSe +c, time_zone => 'America/Los_Angeles' ); } catch { if ( /^Invalid local time for date in time zone/ and $recordMonth == 3 and $recordHour == 2 ) { warn "Looks like invalid DST timestamp\n"; return DateTime->new( year => $recordYear, month => $recordMonth, day => $record +Date, hour => $recordHour +1, minute => $recordMin, second => $r +ecordSec, time_zone => 'America/Los_Angeles' ); } else { die $_; # try to rethrow other exception } return undef; # in case you don't want to return adjusted time }; if ($recordOnPST) { my $recordOnUTC = $recordOnPST -> clone -> set_time_zone('UTC'); print "$recordOnPST \n"; print "$recordOnUTC \n"; }
Ron

Replies are listed 'Best First'.
Re^4: DateTime Invalid local time for date in time zone
by sannag (Sexton) on Jul 11, 2018 at 19:25 UTC
    This is pretty nice. I had the users correct the data so hopefully this error will not occur. I am incorporating a your suggestion and @haukew solution in to my code. Thank you

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1218337]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2022-12-09 00:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?