kht
kht

Reputation: 317

How to calculate the time difference between unix time stamps?

I am creating time stamps in PHP using time();

I have the $current_time and $purchase_time. How do I make sure that purchase_time is less than 24 hours of current time?

Upvotes: 6

Views: 25114

Answers (5)

Adam Fowler
Adam Fowler

Reputation: 1751

Something like this:

$difference=time() - $last_login;

Upvotes: 1

Geert
Geert

Reputation: 1093

You can construct a DateTime object and then use it's diff() method to calculate the difference between $current_time and $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.';
}

This is more reliable than calculating the difference yourself, as this method takes care of timezones and daylight saving time.

Upvotes: 1

Sawny
Sawny

Reputation: 1423

I had use something like this:

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

This works even if the time stamp not is a UNIX-timestamp.

Upvotes: 0

Rene Pot
Rene Pot

Reputation: 24815

If they are UNIX timestamps, then you can calculate this by yourself really easy, as they are seconds.

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

Upvotes: 9

phihag
phihag

Reputation: 287835

Since UNIX timestamps are just numbers of seconds, just use the difference:

$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';
}

Upvotes: 7

Related Questions