0

I have a task module, in it I have two fields

  • t_due_on(task complete date)
  • t_completed_on (task completed date)

Example data:

id        task_name   t_due_on                      t_completed_on   
1         PF Module   2017-03-14 10:15 PM           2017-03-13 23:29 PM

The given task's due date is tomorrow but it was actually finished today, so I need to display the results like:

Task finished: 1 day before
Borislav Sabev
  • 4,776
  • 1
  • 24
  • 30
subikshan M
  • 263
  • 6
  • 17
  • Look at similar questions like this and just adapt it for what you need - http://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php – Peter Mar 13 '17 at 19:07

1 Answers1

0

You can use the DateTime::diff() or DateTimeImmutable::diff() function. All you have to do is to compare the two dates. I have given a very basic example here:

$dt1 = new DateTimeImmutable('2017-03-14 00:00:00');
$dt2 = new DateTimeImmutable('2017-03-16 12:00:00');

$di = $dt2->diff($dt1);
$outputStr = "Task finished: {$di->days} days ";
$suffix = $di->invert == 1 ? 'before' : 'after';
$outputStr .= $suffix . " deadline";

echo $outputStr;

Now it is important to note that:

  • the diff() function will produce a DateInterval class instance. This does not provide methods but rather explains the time interval in terms of seconds, minutes, hours, days, weeks etc.
  • notice that $di->invert is high (== 1) when the interval is -2 days for eg. $di->invert will be 0 for positive differences
  • the order of comparison is important! So calling $dt2->diff($dt1) is not the same as $dt1->diff($dt2) because of how the dates are spaced in time
  • you have to take care of the output. I.e. IF the difference between the two dates is less than a day $di->days will be 0! But $di->h will be set. Thus your functionality has to intelligently handle this also
Borislav Sabev
  • 4,776
  • 1
  • 24
  • 30