Rudi
Rudi

Reputation: 111

PHP: Check if it has been one week since timestamp

Let's assume:

$time = '2010-05-17 02:49:30' // (retrieved from MySQL TIMESTAMP field)

How do I do the following in PHP:

1) Check if it has been more than one week since this time has passed?

2) Assuming "false" on (1), find out how much more time until the one week mark, rounded to days and hours remaining.

I know this is pretty straightforward, but it uses a very specific syntax. Having never played with time calculations before, I'd appreciate some guidance.

Thanks!

Upvotes: 8

Views: 8412

Answers (7)

Mr Vector
Mr Vector

Reputation: 171

SELECT * FROM 'contents'
WHERE (WEEK(NOW(), 7) = WEEK('publish_up', 7)) AND YEAR('publish_up') = YEAR(NOW())

Upvotes: 1

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

Doesn't strtotime let you do things like this...

$timestamp = strtotime($time);
$oneweekago = strtotime("-1 week");
if($oneweekago<=$timestamp) {
    // it's been less than one week
    $secondsleft = $oneweekago - $timestamp;
    // ...
}

Upvotes: 6

user7675
user7675

Reputation:

$time = strtotime('2010-05-10 02:49:30');
$one_week_ago = strtotime('-1 week');

if( $time > $one_week_ago ) { 
    // it's sooner than one week ago
    $time_left = $time - $one_week_ago;
    $days_left = floor($time_left / 86400); // 86400 = seconds per day
    $hours_left = floor(($time_left - $days_left * 86400) / 3600); // 3600 = seconds per hour
    echo "Still $days_left day(s), $hours_left hour(s) to go.";
}

Upvotes: 11

Your Common Sense
Your Common Sense

Reputation: 157875

mysql has a bunch of datetime functions. date_add and datediff among them.
though to count hours could be tricky.
Anyway I can't believe you going to do that comparison using PHP

Upvotes: 0

Robert
Robert

Reputation: 8609

There are lots of great functions for date manipulation. Take a look at this page in the manual http://php.net/manual/en/ref.datetime.php

Upvotes: 0

Amy B
Amy B

Reputation: 17977

Here you are:

$time = strtotime('2010-05-9 02:49:30');
$oneWeekAgo = time() - (7 * 84600);

$hasOneWeekPassed = $time < $oneWeekAgo;
if (!$hasOneWeekPassed)
{
    $timeLeft = $time - $oneWeekAgo;
}

var_dump($hasOneWeekPassed);
var_dump($timeLeft);

Absolutely do NOT do what Col. Shrapnel said (calculate it in MySQL). Not only is it completely unnecessary but that will be at least 20 times slower than the pure PHP above.

Upvotes: -3

zaf
zaf

Reputation: 23264

You can use strptime/strftime (or mysql TIMESTAMP) to parse your time and then check if it is at least one week form the present (one week = 604800 seconds).

If one week has not passed then you can work out how many seconds still remain from which you can calculate days and hours left.

Upvotes: 1

Related Questions