将日期(带毫秒)转换为时间戳
Converting date (with milliseconds) into timestamp
我的日期格式像 '25 May 2016 10:45:53:567'.
我要转换成时间戳
strtotime
函数 returns 为空。
$date = '25 May 2016 10:45:53:567';
echo strtotime($date);
// returns empty
当我删除毫秒时,它起作用了。
$date = '25 May 2016 10:45:53';
echo strtotime($date);
// returns 1464153353
请解决我的问题。提前致谢。
使用DateTime
:
$date = DateTime::createFromFormat('d M Y H:i:s:u', '25 May 2016 10:45:53:000');
echo $date->getTimestamp();
// 1464165953
// With microseconds
echo $date->getTimestamp().'.'.$date->format('u');
// 1464165953.000000
拆分字符串:
$date = '25 May 2016 10:45:53:001';
preg_match('/^(.+):(\d+)$/i', $date, $matches);
echo 'timestamp: ' . strtotime($matches[1]) . PHP_EOL;
echo 'milliseconds: ' . $matches[2] . PHP_EOL;
// timestamp: 1464162353
// milliseconds: 001
使用 Datetime 代替 date 和 strtotime。
//using date and strtotime
$date = '25 May 2016 10:45:53:000';
echo "Using date and strtotime: ".date("Y-m-d H:i:s.u", strtotime($date));
echo "\n";\
//using DateTime
$date = new DateTime();
$date->createFromFormat('d M Y H:i:s.u', '25 May 2016 10:45:53:000');
echo "Using DateTime: ".$date->format("Y-m-d H:i:s.u");
// since you want timestamp
echo $date->getTimestamp();
// Output
// Using date and strtotime: 1969-12-31 16:00:00.000000
// Using DateTime: 2016-05-28 03:25:22.000000
我的日期格式像 '25 May 2016 10:45:53:567'.
我要转换成时间戳
strtotime
函数 returns 为空。
$date = '25 May 2016 10:45:53:567';
echo strtotime($date);
// returns empty
当我删除毫秒时,它起作用了。
$date = '25 May 2016 10:45:53';
echo strtotime($date);
// returns 1464153353
请解决我的问题。提前致谢。
使用DateTime
:
$date = DateTime::createFromFormat('d M Y H:i:s:u', '25 May 2016 10:45:53:000');
echo $date->getTimestamp();
// 1464165953
// With microseconds
echo $date->getTimestamp().'.'.$date->format('u');
// 1464165953.000000
拆分字符串:
$date = '25 May 2016 10:45:53:001';
preg_match('/^(.+):(\d+)$/i', $date, $matches);
echo 'timestamp: ' . strtotime($matches[1]) . PHP_EOL;
echo 'milliseconds: ' . $matches[2] . PHP_EOL;
// timestamp: 1464162353
// milliseconds: 001
使用 Datetime 代替 date 和 strtotime。
//using date and strtotime
$date = '25 May 2016 10:45:53:000';
echo "Using date and strtotime: ".date("Y-m-d H:i:s.u", strtotime($date));
echo "\n";\
//using DateTime
$date = new DateTime();
$date->createFromFormat('d M Y H:i:s.u', '25 May 2016 10:45:53:000');
echo "Using DateTime: ".$date->format("Y-m-d H:i:s.u");
// since you want timestamp
echo $date->getTimestamp();
// Output
// Using date and strtotime: 1969-12-31 16:00:00.000000
// Using DateTime: 2016-05-28 03:25:22.000000