tags:

views:

21

answers:

2

Hi all,

I'm trying to do a function that will check the php date against what is in the database. If the current date (YYYY-MM-DD HH:MM:SS) is 24 hours after the stored database date, then it will continue, otherwise it won't do anything.. If that makes sense?

Here's how I'm trying to get it to work, but not 100% sure how:

$now = date("Y-m-d H:i:s");

foreach($results as $item) {
  if (  /*item date is 24 hours or more earlier than $now*/ ) { /* this is what I'm not sure how to do */
     //do something

  } else {
    //do nothing
  };
};

If someone could help me get this working, I'd greatly appreciate it. I just don't know how to compare $item->date with $now and see if $item->date is 24 hours or more behind $now..

+1  A: 

You can use strtotime instead of date math. Personally I think it reads much better.

if (strtotime($item->date) <= strtotime('-1 day')) {
  // date is more than or equal to 24 hours old
}
Jason McCreary
If $item->date is a string of the format "YYYY-MM-DD HH:MM:SS" a <= comparison wouldn't make sense and it'd probably need a strtotime() on that too. At least that's how I interpreted the format of the date from the database.
thomasrutter
You are correct. You would need to `strtotime($item->date)`. I have updated my code.
Jason McCreary
+1  A: 
foreach($results as $item) {
  if (time() >= strtotime($item['date']) + 86400) {
    // current time is 86400 (seconds in one day) or more greater than stored time
  } else {
    //do nothing
  };
};

Note that if the stored date isn't in the same timezone as the server you'll need to mess with timezones - see here for starters.

Note that I store dates and times in MySQL as Unix timestamps to avoid some of these problems. I know it's not good database practice, but then PHP stores times as Unix timestamps anyway.

thomasrutter