Search code examples
perldatetimeformatiso8601strptime

How to convert unknown date/time format into normal using Perl?


I have a date/time like this: 2015-07-31T13:30:00.000+01:00 And I want to convert it to normal date and time using Perl and Time::Piece->strptime

Here is my code:

sub changeDateFormat {
  my ($date, $fromFormat, $toFormat) = (@_);
  return Time::Piece->strptime($date, $fromFormat)->strftime($toFormat);
}

The call:

print changeDateFormat($that_date, '%Y-%m-%dT%H:%M:%S.%N+%z', '%Y:%m:%d');

I think that .000 are nano seconds and +01.00 stands for time zone. But the given code gives this: Error parsing time at /usr/lib64/perl5/Time/Piece.pm line 470

Any help is appreciated.


Solution

  • There's a couple of problems I think.

    %N isn't in my strftime manpage. So that might well not work.

    And %z - I'm pretty sure +01:00 isn't valid.

      %z     The +hhmm or -hhmm numeric timezone (that is, the hour and
              minute offset from UTC). (SU)
    

    This works though:

    my $date = '2015-07-31T13:30:00+0100'; 
    my $fromFormat = '%Y-%m-%dT%H:%M:%S%z'; 
    print Time::Piece->strptime($date, $fromFormat);
    

    So I'd suggest - unless your milliseconds are important - you could just strip those via a regex, and likewise the timezone. (And it they are important, I don't think Time::Piece does ms resolution anyway)

    You can probably use a regular expression to 'correct' your input date if you were so inclined. I'm unsure if fits your use case but:

    $date =~ s/\+(\d{2}):(\d{2})$/+$1$2/;
    $date =~ s/\.\d{3}+/+/;