Sunday, April 3, 2011

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.

From stackoverflow
  • 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;
    }
    
    ysth : \b is redundant between \d+ and [+-]. I'd remove the 2nd & 3rd \b and add one at the end.

0 comments:

Post a Comment