1
votes

I have two fields with datetime formats in Symfony 2.Now I want to get total hours after the form is submitted

entity.php

 private $timein;
 private $timeout;

 public function setTimein($timein)
 {
 ......
 public function getWorkHour()
 {
    $hour1 = 0; $hour2 = 0;
    $date1 = $this->timein;
    $date2 = $this->timeout;
    $datetimeObj1 = new \DateTime($date1);
    $datetimeObj2 = new \DateTime($date2);
    $interval = $datetimeObj1->diff($datetimeObj2);

    if($interval->format('%a') > 0){
        $hour1 = $interval->format('%a')*24;
    }
    if($interval->format('%h') > 0){
        $hour2 = $interval->format('%h');
    }

    $hour = ($hour1 + $hour2) . " hours.";
    return $hour;
}

show.html

 <th>No of Hour</th>
 <td>{{ entity.getWorkHour() }}</td>

This will throw an error

An exception has been thrown during the rendering of a template ("DateTime::__construct() expects parameter 1 to be string, object given") in ...

How would you simply get number of hours between two hours in same date?

3
simply try $interval = $this->timeout->diff($this->timein)Matteo

3 Answers

1
votes

You can do like this

    $currentDate = new \DateTime();
    $lastDate = new \DateTime(); // your own date
    $diff = $currentDate->diff($lastDate);
    $hours = $diff->h;
    $hours = $hours + ($diff->days * 24);
    echo $hours;
0
votes

Your error means that $this->timein or $this->timeout are not string, so dump them and check your code (who set them, etc).

As for difference between dates, you need:

  • convert them to timestamps

  • get the diff between them and convert it to hours.

0
votes

You must write your custom twig extension:

You must write a twig function as described here with the following code for make diff via php function:

$calcFrom = $from;

$calcTo = $to;
$diff = $now->diff($calcFrom);
$workHours = $diff->days * 24 + (int)$diff->format('%H');

And make it available via a Twig extension. See here also.

If you are using symfony2 framework You can use the KnpTimeBundle

In the Twig: This compare with the current date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(form) }}

This compare with the another date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(form , to ) }}

Hope this help