Search code examples
phpmysqldatetimeunix-timestamp

Calculate Time difference using UNIX time stamp in PHP


I have 2 unix time, one is todays date and other is expiration time.

  • Todays Time: 1377173245 (2013-08-22 12:07:25)
  • Expiration Time: 1406303166 (2014-07-25 15:46:06)

What I want to achieve is calculate remaining time to expire the listing. In current case, it should show, 11 months -- hours -- minutes -- seconds I didn't find any good solution to calculate the difference. I doubt is it possible to calculate time difference using UNIX time system?

Thank you :-)


Solution

  • This is what you're looking for: DateTime::diff

    First create object with 1st date:

    $date = new DateTime('2013-08-22 12:07:25');
    

    Then use the diff method:

    $diff = $date->diff(new DateTime('2014-07-25 15:46:06'));
    

    Now if you print $diff variable, you will see the array containing values for hour, minute, day and so on.