How would I check if a date in the format "2008-02-16 12:59:57" is less than 24 hours ago?
+2
A:
e.g. via strtotime and time().
The difference must be less then 86400 (seconds per day).
<?php
echo 'now: ', date('Y-m-d H:i:s'), "\n";
foreach( array('2008-02-16 12:59:57', '2009-12-02 13:00:00', '2009-12-02 20:00:00') as $input ) {
$diff = time()-strtotime($input);
echo $input, ' ', $diff, " ", $diff < 86400 ? '+':'-', "\n";
}
prints
now: 2009-12-03 18:02:29
2008-02-16 12:59:57 56696552 -
2009-12-02 13:00:00 104549 -
2009-12-02 20:00:00 79349 +
only the last test date/time lays less than 24 hours in the past.
VolkerK
2009-12-03 16:59:36
It's ok (i suppose) in the case where he needs "less than 24 HOURS". Just keep in mind not to assume that a day always has 24h (like you said in your answer). If you move from hours difference to days difference, you're better off using a DateTime library. For a better explanation of Time issues, you can check this article: http://www.odi.ch/prog/design/datetime.php
Carlos Lima
2009-12-03 18:55:45
+2
A:
if ((time() - strtotime("2008-02-16 12:59:57")) < 24*60*60) {
// less than 24 hours ago
}
Dominic Rodger
2009-12-03 17:00:00
from manual: Note: As of PHP 5.1, when called with no arguments, mktime() throws an E_STRICT notice: use the time() function instead.
Tom Haigh
2009-12-03 17:02:51
+1
A:
Php has a comparison function between two date/time objects, but I don't really like it very much. It can be imprecise.
What I do is use strtotime() to make a unix timestamp out of the date object, then compare it with the output of time().
Satanicpuppy
2009-12-03 17:03:00
+10
A:
if (strtotime("2008-02-16 12:59:57") >= time() - 24 * 60 * 60)
{ /*LESS*/ }
Don
2009-12-03 17:04:03
+2
A:
Just adding another answer, using strtotime
's relative dates:
$date = '2008-02-16 12:59:57';
if (strtotime("$date +1 day") <= time()) {
// Do something
}
I think this makes the code much more readable.
LiraNuna
2009-12-07 10:57:36