datetime - Parsing dates with correct time zone in perl with core modules only -
i have several checks dates read database. instance, have compare them perl script's local time. have determine calendar date of parsed date. in order have readable code, i have identical time zone information in both generated (localtime
) , parsed (strptime
) time objects.
the solution should 1-file only, task should done core perl modules (version 5.10). datetime
module doesn't seem option.
the closest have come time::piece
, there seems no way time object parsing identical 1 obtained time::piece::localtime()
.
use time::piece; use strict; use warnings; use 5.010; sub mystrptime1 { $datestr = shift; $tzoffset = sprintf '%+03d00', localtime->tzoffset->hours; $t = time::piece->strptime("$datestr $tzoffset", '%y%m%d %h:%m:%s %z'); } sub mystrptime2 { $datestr = shift; $t = time::piece->strptime($datestr, '%y%m%d %h:%m:%s'); # interpreted gmt, subtract time zone offset :-( return $t - time::piece::localtime->tzoffset; } $format = '%y%m%d %h:%m:%s'; $strptime (\&mystrptime1, \&mystrptime2) { $lt = time::piece::localtime(); "localtime $lt, tz offset ", $lt->tzoffset(); $str = $lt->strftime($format); "str $str"; $g = $strptime->( $str ); "parsed time $g, tz offset ", $g->tzoffset(); "time difference is: ", $lt-$g; "hour difference is: ", $lt->hour - $g->hour; }
what want both hour difference , time difference of zero, seems impossible.
i able make both solutions work by calling localtime
on strptime
result:
sub mystrptime1 { $datestr = shift; $tzoffset = sprintf '%+03d00', localtime->tzoffset->hours; $t = time::piece->strptime("$datestr $tzoffset", '%y%m%d %h:%m:%s %z'); return time::piece::localtime($t->epoch); } sub mystrptime2 { $datestr = shift; $t = time::piece->strptime($datestr, '%y%m%d %h:%m:%s'); # interpreted gmt, subtract time zone offset :-( $t -= time::piece::localtime->tzoffset; return time::piece::localtime($t->epoch); }
Comments
Post a Comment