@Brombomb
Your Function works fine, but there is one thing you forgot.
Timestamps can be negative for Dates before the 01.01.1970, so we need a different regEx
I used this one and it works fine:
preg_match( '/\/Date\((-?\d+)([+-]\d{4})\)/', $date, $matches);
At the end i modified your Function a little bit to become more usefull for me.
Now i can decide if i get the Date back as
- "date" => date only
- "time" => time only
- "datetime" => date and time
- "array" => date and time as an array
- "string" => the timestamp as a string
and i can decide if i want the difference to the UTC timezone added/substracted when i give the third parameter...
function parseJsonDate($date, $type = 'date', $utc = 0) {
// Match the time stamp (microtime) and the timezone offset (may be + or -) and also negative Timestamps
preg_match( '/\/Date\((-?\d+)([+-]\d{4})\)/', $date, $matches);
$seconds = $matches[1]/1000; // microseconds to seconds
$UTCSec = $matches[2]/100*60*60; // utc timezone difference in seconds
if($utc != 0){
$seconds = $seconds + $UTCSec; // add or divide the utc timezone difference
}
$date = date( 'Y-m-d', $seconds ); // only date
$dateTime = date( 'Y-m-d H:i:s', $seconds ); // date and time
$time = date( 'H:i:s', $seconds ); // only time
switch($type)
{
case 'date':
return $date; // returns 'YYYY-MM-DD'
break;
case 'datetime':
return $dateTime; // returns 'YYYY-MM-DD HH:ii:ss'
break;
case 'time':
return $time; // returns 'HH:ii:ss'
break;
case 'array':
$dateArray = str_replace(" ", "-", $dateTime);
$dateArray = str_replace(":", "-", $dateArray);
return explode('-', $dateArray); // return array('YYYY', 'MM', 'DD', 'HH', 'ii', 'SS')
break;
case 'string':
return $matches[1] . $matches[2]; // returns 1336197600000-0600
break;
}
}