如何从 PHP 日期时间获取 unix 时间戳?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12802987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a unix timestamp from PHP date time?
提问by user1216398
I'm trying to get a unix timestamp with PHP but it doesn't seem to be working. Here is the format I'm trying to convert to a unix timestamp:
我正在尝试使用 PHP 获取 unix 时间戳,但它似乎不起作用。这是我尝试转换为 unix 时间戳的格式:
PHP
PHP
$datetime = '2012-07-25 14:35:08';
$unix_time = date('Ymdhis', strtotime($datetime ));
echo $unix_time;
My result looks like this:
我的结果是这样的:
20120725023508
Any idea what I'm doing wrong?
知道我做错了什么吗?
回答by Baba
回答by Niklas Modess
This is converting it to a unix timestamp: strtotime($datetime), but you're converting it back to a date again with date().
这是将其转换为 unix timestamp: strtotime($datetime),但您再次将其转换回日期date().
回答by Marcel
To extend the answers here with an object-oriented solution, the DateTime class must be named. The DateTime class is available since PHP 5.2 and can be used as follows.
要使用面向对象的解决方案扩展此处的答案,必须命名 DateTime 类。DateTime 类从 PHP 5.2 开始可用,可以按如下方式使用。
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2012-07-25 14:35:08');
echo $date->getTimestamp(); // output: 1343219708
Or even as a one-liner
甚至作为单线
echo $date = (new DateTime('2012-07-25 14:35:08'))->getTimestamp();
// output: 1343219708

