tags:

views:

675

answers:

1

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.

+5  A: 

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, $timezone ) = ( $1, $2 );
    my $dt = DateTime->from_epoch( epoch => $epoch_milliseconds / 1000 );
    if ($time_zone) {
        $dt->set_time_zone($time_zone);
    }
    print $dt->datetime;
}
Anirvan
ysth