- vsprintf: documentation ( source)
- preg_match: documentation ( source)
- sprintf: documentation ( source)
<?php
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(1440960660000+0200)/';
$parser = new JsonTimestampWithOffsetParser;
$dt = $parser->parse($date);
//$dt->modify();
echo $dt->format('Z');
echo $dt->format('Y-m-d H:i:s');