简体   繁体   中英

Check if datetime value is from last 30 days in php (not in the mysql query)?

I need to check with php if values got from a database are from last 30 days.

The values are formatted as follows:

2012-03-19 05:00:32

How can this be done?

You can use strtotime to turn it to a unix timestamp.

$db_date = "2012-03-19 05:00:32";
if (time() - strtotime($db_date) <= 30 * 86400) {
  //...
}
$date = '2012-03-19 05:00:32';
if (strtotime($date) >= strtotime('-30 days')) {
    // do something
}

See strtotime() reference .

You could do it in PHP, but that'd mean a roundtrip through the date/time system to process that string back into a date value:

$within_30 = ((strtotime('2012-03-19 05:00:32') + 30*86400) > time());

Assumign you're using MySQL, you could do it in the query directly, and save some time conversions:

SELECT ((yourtimefield + INTERVAL 30 DAY) > now()) AS within_30 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM