使用PHP中的UNIX时间戳计算时间差[重复]

This question already has an answer here:

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 :-)

</div>

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.

Try using datetime::diff. Here's the example from the php.net documentation:

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

It's easy to create a DateTime object using a timespamp. However, this solution requires PHP 5.3+.

It is most definitely possible. However, you'll run into problems with months, because there are different number of days in each month, so I'll just do days, hours, minutes, and seconds below.

$days=($expiration-$today)/(60*60*24);
$hours=(($expiration-$today)/(60*60))%24; //the modulus operator, gets a remainder
$minutes=(($expiration-$today)/(60))%(60*60);
$seconds=($expiration-$today)/60;

If you need months, you'll find it easier to use date_diff().

Use DateTime::diff

See the doc on http://www.php.net/manual/fr/datetime.diff.php

Use DateTime class:

Example:

$datetime1 = new DateTime();
$datetime2 = new DateTime('2014-07-25 15:46:06');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%M months, %H hours, %I minutes, and %S seconds remaining ');

Outputs:

11 months, 21 hours, 44 minutes, and 20 seconds remaining