我如何在symfony2中将日期对象转换为时间

时间:2012-10-09 15:10:39

标签: date datetime symfony

我正在使用Symfony2。从数据库中提取日期时,我需要在index.html.php中显示日期。

当我打印它的显示时:DateTime Object ( [date] => 2012-10-09 13:30:23 [timezone_type] => 3 [timezone] => UTC )

但是当我将对象转换为int时,它给出了错误:$days2 = floor( $entities->getCreationDate() / (60 * 60 * 24));

Notice: Object of class DateTime could not be converted to int**

3 个答案:

答案 0 :(得分:5)

我将此添加为第二个答案,因为它与我之前的答案非常不同。

要在PHP中获取两个日期之间的差异,您可能需要考虑使用PHP的内置DateTime和DateInterval类。

以下代码将为您提供创建日期与今天之间的天数差异:

$creationDate = $entity->getCreationDate();
$now = new \DateTime();

$interval = $creationDate->diff($now);

echo "The difference is " . $interval->days . " days.";

有关DateInterval的更多文档:http://www.php.net/manual/en/class.dateinterval.php

答案 1 :(得分:5)

如果要从DateTime对象获取整数时间戳,请使用getTimeStamp method

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

答案 2 :(得分:0)

在Twig中显示DateTime对象的最佳方法是使用Twig的内置date函数:

{{ entity.creationDate | date("m/d/Y") }}

您实际上可以使用本机PHP函数strtotime()支持的任何格式,因此您可以自定义它的显示方式。以下是您在上面引用的实例的一些示例:

{{ entity.creationDate | date("m/d/Y") }}
--> Prints: "10/09/2012"

{{ entity.creationDate | date("Y-m-d") }}
--> Prints: "2012-10-09"

{{ entity.creationDate | date("H:i") }}
--> Prints: "13:30"

此处有关此Twig功能的更多信息: http://twig.sensiolabs.org/doc/filters/date.html