Datetime到Unix时间戳

问题描述 投票:14回答:6

是否有人坐在PHP函数上将format 0000-00-00 00:00:00(datetimesql)的日期转换为unix时间戳?

php timestamp
6个回答
30
投票

要在PHP 5.2中执行此操作,您可以执行以下操作:

$datetime = new DateTime();
echo $datetime->format('U');

从PHP 5.3开始,更新的方法是:

$datetime = new DateTime();
echo $datetime->getTimestamp();

24
投票

你用SQL标记这个问题的另一个选择:MySQL函数FROM_UNIXTIMEUNIX_TIMESTAMP - > MySQL manual

SELECT UNIX_TIMESTAMP(datetime_column) FROM table

这通常比PHP函数调用快。


9
投票

@bartek - 正如你所说,PHP的strtotime功能非常适合这一点。它可以处理大多数常见的日期格式,包括“明天”或“+ 5个月”等字符串。


5
投票

使用strptime()解析时间并将其转换为结构化数组。

然后将其结果传递给mktime()函数以获取UNIX时间戳。


4
投票

我在这里有一个解决方案:

/* 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);
}

-3
投票

将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];
}
© www.soinside.com 2019 - 2024. All rights reserved.