当前位置: 动力学知识库 > 问答 > 编程问答 >

datetime - How I can convert date object into time in symfony2

问题描述:

I am using Symfony2. While fetching date from database, I need to display date in my index.html.php .

When I am printing its displaying like this: DateTime Object ( [date] => 2012-10-09 13:30:23 [timezone_type] => 3 [timezone] => UTC )

But when I'm converting object to int its giving error: $days2 = floor( $entities->getCreationDate() / (60 * 60 * 24));

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

网友答案:

I'll add this as a second answer, since it's very different than my previous.

To get the difference between two dates in PHP, you may want to consider using PHP's built-in DateTime and DateInterval classes.

The following code will get you the difference, in days, between the creation date and today:

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

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

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

Further documentation on DateInterval: http://www.php.net/manual/en/class.dateinterval.php

网友答案:

If you want to get an integer timestamp from a DateTime object use the getTimeStamp method.

$date = new DateTime();
echo $date->getTimestamp();
网友答案:

The best way to display a DateTime object in Twig is to use Twig's built-in date function:

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

You can actually use any format that's supported by the native PHP function strtotime(), so you can customize how you want it to appear. Here are some examples with the instance you referenced above:

{{ 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"

More info on this Twig function here: http://twig.sensiolabs.org/doc/filters/date.html

分享给朋友:
您可能感兴趣的文章:
随机阅读: