如何计算unix时间戳之间的时差?

时间:2011-10-15 15:58:39

标签: php

我使用 time() ;

在PHP中创建时间戳

我有$current_time$purchase_time。如何确保purchase_time小于当前时间的24小时?

5 个答案:

答案 0 :(得分:7)

由于UNIX时间戳只是秒数,所以只需使用差异:

$purchasedToday = $current_time - $purchase_time < 24 * 60 * 60;
if ($purchasedToday) {
  echo 'You just bought the item';
} else {
  echo 'You bought the item some time ago';
}

答案 1 :(得分:7)

如果它们是UNIX时间戳,那么你可以很容易地自己计算,因为它们是秒。

$seconds = $current_time - $purchase_time
$hours = floor($seconds/3600);
if ($hours < 24){
    //success
}

答案 2 :(得分:1)

您可以构造一个DateTime对象,然后使用它的diff()方法来计算$ current_time和$ purchase_time之间的差异:

$currentTime = new DateTime();
$purchaseTime = new DateTime('2011-10-14 12:34:56');

// Calculate difference:
$difference = $currentTime->diff($purchaseTime);

if ($difference->days >= 1) {
    echo 'More than 24 hours ago.';
}

这比自己计算差异更可靠,因为这种方法可以处理时区和夏令时。

答案 3 :(得分:1)

这样的事情:

$difference=time() - $last_login;

答案 4 :(得分:0)

我曾经使用过这样的东西:

<?php
if(date("U", strtotime("-24  hours", $current_time) > date("U", $purchase_time)) {
    echo "More then 24 hours you purchased this radio";
}
?>

即使时间戳不是UNIX时间戳,也能正常工作。

相关问题