expected start and end datetime difference

6997

error.png

there are 3 fields in task table-> expected_start_datetime,expected_end_datetime,time_allocated

While creating a task expected start and end datetime is selected and saved in the records.

What I am trying to do is to find the difference between the two dates in hours and minutes and save the value inside the "time_allocated" while creating the task and later on the update or view page use/display the time allocated value from the records.

DateTime::diff can help you with finding the difference:

http://php.net/manual/en/datetime.diff.php

You can put the code in your model’s “beforeSave”:

http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#beforeSave()-detail

I got the time difference using the below in the beforeSave of Task model

$this->time_allocated =date(‘H:i’,(strtotime($this->expected_end_datetime)-strtotime($this->expected_start_datetime)));

but the difference I am getting by this is always wrong

Untested but try something like this:




$expectedStartTime = new DateTime($this->expected_start_datetime);

$expectedEndTime = new DateTime($this->expected_end_datetime);

$diff = $expectedEndTime->diff($expectedStartTime, true);

$hours = $diff->h + ($diff->days*24);