get a time difference between two dates

2019-02-21 06:13发布

问题:

I would like compare the two dates to get a time (Days, Hours, minutes and seconds) difference in TWIG

{% set todayDate = ( "now"| date("Y-m-d H:i:s") ) %}  //2013-04-17 08:45:28 
{% set endDate =  (enddate|date('Y-m-d H:i:s')) %}    //2013-04-18 23:59:59

How to get hours difference?

回答1:

Finally i got it.. compare the two dates to get a time (Days, Hours and minutes) in controller :

(doctrine query)

TIMESTAMPDIFF(DAY,CURRENT_TIMESTAMP(), a.enddate) AS endday,    
(TIMESTAMPDIFF(HOUR,CURRENT_TIMESTAMP(), a.enddate) - TIMESTAMPDIFF(DAY,CURRENT_TIMESTAMP(),a.enddate)*24) AS endhour,
(TIMESTAMPDIFF(MINUTE,CURRENT_TIMESTAMP(), a.enddate) - TIMESTAMPDIFF(HOUR,CURRENT_TIMESTAMP(), a.enddate)*60) AS endmin,

Created a function for TIMESTAMPDIFF https://github.com/beberlei/DoctrineExtensions/blob/master/lib/DoctrineExtensions/Query/Mysql/TimestampDiff.php

and include a snippet

app->config->config.yml doctrine: dbal: ........

orm:
    entity_managers:
        default:
            auto_mapping: true
            dql:
                datetime_functions:
                    timestampdiff: Acme\BUNDLE\FOLDER\TimestampDiff

Thanks to all ..



回答2:

Since you pass the enddate to your template, you should do this in your controller and pass the result to your template.

Here is the php code you could use:

$now = new DateTime('now');
$dateToCompare = new DateTime('your date');

$difference = $now->format('U') - $dateToCompare->format('U');
// or if your date to compare is in the future :
// $difference = $dateToCompare->format('U') - $now->format('U');
$time_diff = gmdate('H',$difference);

echo $time_diff;