pauld78
pauld78

Reputation: 43

Time difference between unix timestamps

I have to try and work out if a unix timestamp is between 21 days and 49 days from the current date. Can anyone help me to work this out? Thanks!

Upvotes: 1

Views: 1415

Answers (3)

David Titarenco
David Titarenco

Reputation: 33406

Welcome to SO!
This should do it:

if (($timestamp > time() + 1814400) && ($timestamp < time() + 4233600)) {
 // date is between 21 and 49 days in the FUTURE
}

This can be simplified, but I thought you wanted to see a more verbose example :)

I get 1814400 from 21*24*60*60 and 4233600 from 41*24*60*60.

Edit: I assumed future dates. Also note time() returns seconds (as opposed to milliseconds) since the Epoch in PHP.

This is how you do it in the past (since you edited your question):

if (($timestamp > time() - 4233600) && ($timestamp < time() - 1814400)) {
 // date is between 21 and 49 days in the PAST
}

Upvotes: 5

nikc.org
nikc.org

Reputation: 16993

strtotime is very useful in these situations, since you can almost speak natural english to it.

$ts; // timestamp to check
$d21 = strtotime('-21 days');
$d49 = strtotime('-49 days');

if ($d21 > $ts && $ts > $d49) {
    echo "Your timestamp ", $ts, " is between 21 and 49 days from now.";
}

Upvotes: 3

Jon Cram
Jon Cram

Reputation: 17309

The PHP5 DateTime class is very suited to these sort of tasks.

$current = new DateTime();
$comparator = new DateTime($unixTimestamp);
$boundary1 = new DateTime();
$boundary2 = new DateTime();

$boundary1->modify('-49 day'); // 49 days in the past
$boundary2->modify('-21 day'); // 21 days in the past

if ($comparator > $boundary1 && $comparator < $boundary2) {
    // given timestamp is between 49 and 21 days from now
}

Upvotes: 3

Related Questions