将PHP中的日期时间转换为秒数

18

我在 mysql 中有一个日期时间值 '2010-12-08 16:12:12',
我希望使用 PHP 获取到该日期的秒数,
也就是说需要一个与 mysql 等价的 PHP 函数:

TIME_TO_SEC(TIMEDIFF('2010-12-08 16:12:12',now()))
4个回答

27
<?php

$date1 = new DateTime("2010-12-08 16:12:12");
$now = new DateTime();

$difference_in_seconds = $date1->format('U') - $now->format('U');

->format('U') 将其转换为Unix时间戳。


6
$date->getTimestamp()可能更好一些。@notJim,参考文档:http://php.net/manual/zh/datetime.gettimestamp.php - relipse
谢谢!这个('U')格式实际上非常有用! - b0rgBart3

22

这不是真的,因为 time() 大于数据库中旧的时间戳行。 - Egor

1

尝试

$time_diff = time() - strtotime('2010-12-08 16:12:12');

-2

mktime()无法转换MySQL格式日期(2010-12-08 16:12:12)。 - Thiago Belem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接