I have an iso8601 time string to parse in $str, and
a default timezone id in $tzid, which is to be used
if $str has no timezone.

I want to get an epoch.

here is my implementation:

sub iso_to_epoch {
    my ($str, $defaulttz) = @_;
    my $dt = DateTime::Format::ISO8601->parse_datetime( $str );
    $dt->set_time_zone($defaulttz) if $dt->time_zone_long_name() eq
    'floating' && $defaulttz;
    return $dt->epoch();
}

The above does work.
However, it isn't particular clean, requiring 3 calls.

I suppose I could specify the default timezone first:

sub iso_to_epoch {
   my ($str, $defaulttz) = @_;
   my $basedt = DateTime->new(time_zone => $defaulttz);
   my $iso8601 = DateTime::Format::ISO8601->new(base_datetime =>
   $basedt);
   my $dt = $iso8601->parse_datetime($str);
   return $dt->epoch();
}

but that is about as many lines.

Here are some hypothetical ways this might be shortened:

return DateTime::Format::ISO8601->parse(str => $str, default_time_zone
=> $defaulttz)->epoch()

return DateTime->parse(format => 'ISO8601', str => $str, base_datetime
=> {time_zone => $defaulttz})->epoch()


-mda

Reply via email to