Dave
Dave

Reputation: 5634

How do I parse the JSON Date Format in Perl?

How can I parse this date format that my web service is receiving in JSON format in Perl? I'd like to convert it to a DateTime object:

Date(1216647000000-0400)

I assumed it was milliseconds since the epoch along with a time zone offset but the dates are way off.

Upvotes: 3

Views: 2599

Answers (1)

Anirvan
Anirvan

Reputation: 6364

The time is listed in milliseconds since the epoch. Divide by 1000 to get epoch seconds.

Make sure this works with other cases you encounter:

use DateTime;

my $json_date = 'Date(1216647000000-0400)';
if ($json_date =~ m{ \b (\d+) \b ([+-]\d\d\d\d\b)? }x ) {
    my ( $epoch_milliseconds, $time_zone ) = ( $1, $2 );
    my $dt = DateTime->from_epoch( epoch => $epoch_milliseconds / 1000 );
    if ($time_zone) {
        $dt->set_time_zone($time_zone);
    }
    print $dt->datetime;
}

Upvotes: 8

Related Questions