php 日期时间到 Unix 时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/455554/
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
Datetime To Unix timestamp
提问by wvanbergen
Is there anyone sitting on a PHP function to convert a date of format 0000-00-00 00:00:00(datetimesql) to unix timestamp?
有没有人坐在 PHP 函数上将格式 0000-00-00 00:00:00(datetimesql) 的日期转换为 unix 时间戳?
回答by John Conde
To do this in PHP 5.2 you can do this:
要在 PHP 5.2 中执行此操作,您可以执行以下操作:
$datetime = new DateTime();
echo $datetime->format('U');
A newer way to do this as of PHP 5.3 is:
从 PHP 5.3 开始,一种更新的方法是:
$datetime = new DateTime();
echo $datetime->getTimestamp();
回答by wvanbergen
Another option as you have tagged this question with SQL: the MySQL functions FROM_UNIXTIMEand UNIX_TIMESTAMP-> MySQL manual
另一个选项,因为你用 SQL 标记了这个问题:MySQL 函数FROM_UNIXTIME和UNIX_TIMESTAMP-> MySQL 手册
SELECT UNIX_TIMESTAMP(datetime_column) FROM table
This usually is faster than a PHP function call.
这通常比 PHP 函数调用快。
回答by ceejayoz
回答by Alnitak
Use strptime()to parse the time and turn it into a structured array.
使用strptime()解析的时间,把它变成一个结构化的阵列。
Then pass the results of that into the mktime()function to get a UNIX timestamp.
然后将其结果传递给mktime()函数以获取 UNIX 时间戳。
回答by deepcell
I have a solution for you right here:
我在这里为您提供解决方案:
/* From MySQL datetime to Unix Timestamp 2003-12-30 23:30:59 -> 1072834230 */
function convertMysqlDateTimeToUnixTimeStamp($date) {
$yr=strval(substr($date,0,4));
$mo=strval(substr($date,5,2));
$da=strval(substr($date,8,2));
$hr=strval(substr($date,11,2));
$mi=strval(substr($date,14,2));
$se=strval(substr($date,17,2));
return mktime($hr,$mi,$se,$mo,$da,$yr);
}
回答by johnboiles
Encapusulating wvanbergen's solution into a function (for your convenience)
将 wvanbergen 的解决方案封装成一个函数(为了您的方便)
//Convert SQL datetime to unixtime -- by johnboiles
function datetimeToUnixtime($datetime){
$result = mysql_query("select unix_timestamp('$datetime')");
$unixtime = mysql_fetch_array($result);
return $unixtime[0];
}

