How to calculate time difference in PHP? [duplicate]

Use the diff() method of PHP’s DateTime class like this:-

$lastWeek = new DateTime('last thursday');
$now = new DateTime();
var_dump($now->diff($lastWeek, true));

This will give you a DateInterval object:-

object(DateInterval)[48]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 2
  public 'h' => int 11
  public 'i' => int 34
  public 's' => int 41
  public 'invert' => int 0
  public 'days' => int 2

Retrieving the values you want from that is trivial.

Leave a Comment