tags:

views:

139

answers:

7

Hi guys,

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!

+1  A: 

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.

zaf
Good approach - didn't think to boil it down that way. Thanks.
Rudi
A: 
Coronatus
whoa. got proof? what if I gonna filter records out from a big table? should I not use mysql too?
Col. Shrapnel
Did you seriously just ask for proof that an extra MySQL query is slower than even non-APC PHP? Go home...
Coronatus
why should it be slower in mysql? if he is querying from the database, he can easily select an additional boolean field `DATE_ADD(my_timestamp, ONE_WEEK) < NOW() AS older_than_one_week` (can't remember the exact syntax now). this seems more sane than mixing two languages
knittl
I think we should do some benchmarking!
zaf
@coronatus who said **extra** query?
Col. Shrapnel
+2  A: 

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;
    // ...
}
LeguRi
+1 nice........ and you should have got the green tick. Bad luck.
zaf
@zaf - thanks :)
LeguRi
A: 

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

Robert
A: 

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

Col. Shrapnel
+2  A: 
$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.";
}
Adam Backstrom
Perfect - thanks. Basically same to what Coronatus supplied, but more fleshed out.
Rudi
I would be curious on the time difference between UNIX_TIMESTAMP() in MySQL and strtotime() in PHP on a large dataset.
Adam Backstrom
A: 

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