Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check if it has been one week since timestamp

Tags:

php

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!

like image 993
Rudi Avatar asked May 16 '10 19:05

Rudi


3 Answers

$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.";
}
like image 164
Annika Backstrom Avatar answered Nov 19 '22 03:11

Annika Backstrom


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;
    // ...
}
like image 39
Richard JP Le Guen Avatar answered Nov 19 '22 04:11

Richard JP Le Guen


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.

like image 1
zaf Avatar answered Nov 19 '22 05:11

zaf