PHP date format /Date(1365004652303-0500)/

First you need to understand the format you have

/Date(1365004652303-0500)/

Then you have

  • time stamp (U) = 1365004652
  • Milliseconds (u) = 303
  • Difference to Greenwich time (GMT) (O) = -0500

Build a Format

$date = '/Date(1365004652303-0500)/';
preg_match('/(\d{10})(\d{3})([\+\-]\d{4})/', $date, $matches);
$dt = DateTime::createFromFormat("U.u.O",vsprintf('%2$s.%3$s.%4$s', $matches));
echo $dt->format('r');

Output

Wed, 03 Apr 2013 15:57:32 -0500
                            ^
                            |= Can you see the GMT ? 

interface DateFormatParser
{
    /**
     * @param $string
     *
     * @return DateTime
     */
    public function parse($string);

}

abstract class PregDateParser implements DateFormatParser
{
    protected $pattern, $format, $mask;

    public function parse($string) {
        $string = (string)$string;

        $pattern = $this->pattern;
        $format  = $this->format;
        $mask    = $this->mask;

        $r = preg_match($pattern, $string, $matches);
        if (!$r) {
            throw new UnexpectedValueException('Preg Regex Pattern failed.');
        }
        $buffer = vsprintf($mask, $matches);
        $result = DateTime::createFromFormat($format, $buffer);
        if (!$result) {
            throw new UnexpectedValueException(sprintf('Failed To Create from Format "%s" for "%s".', $format, $buffer));
        }
        return $result;
    }
}

class JsonTimestampWithOffsetParser extends PregDateParser
{
    protected $pattern = '/^\/Date\((\d{10})(\d{3})([+-]\d{4})\)\/$/';
    protected $format  = 'U.u.O';
    protected $mask    = '%2$s.%3$s.%4$s';
}

$date   = '/Date(1365004652303-0500)/';
$parser = new JsonTimestampWithOffsetParser;
$dt     = $parser->parse($date);

echo $dt->format('r');

Try this out:

var_dump(date('Y-m-d H:i:s', '1365004652303'/1000));
$str = '/Date(1365004652303-0500)/';

$match = preg_match('/\/Date\((\d+)([-+])(\d+)\)\//', $str, $date);

$timestamp = $date[1]/1000;
$operator = $date[2];
$hours = $date[3]*36; // Get the seconds

$datetime = new DateTime();

$datetime->setTimestamp($timestamp);
$datetime->modify($operator . $hours . ' seconds');
var_dump($datetime->format('Y-m-d H:i:s'));

Returns:

string(19) "2013-04-03 17:57:32"
string(19) "2013-04-03 12:57:32"

Let's break /Date(1365004652303-0500)/ down to:

  • Date
  • 1365004652303
  • -0500

First string makes itself pretty clear.

The next large number is the epoch value

The -0500 represents the timezone in which the dates were originally stored. It is relative to UTC and thus, it is referring to Eastern Standard Time.


EDIT

The epoch is with a milisecond precision. Try this code:

<?php
    $str = "/Date(1365004652303-0500)/";
    preg_match( "#/Date\((\d{10})\d{3}(.*?)\)/#", $str, $match );
    echo date( "r", $match[1] );
?>

You can also use the timezone for setting the date relative to your own. http://codepad.viper-7.com/RrSkMy

Tags:

Php

Date

Json