简体   繁体   中英

What is the 'best' way to check if a mySQL date is in the past in PHP?

So I have a database which stores a date-time value. I want to find out if the date is in the past - I don't care about the time part in this instance, just the date.

So I have the following code at the moment

//this is the current date
$today = strtotime(date("Y-m-d"));
//this is the date from the database
$gameDate = strtotime($rec[0])
if (strtotime($rec[0]) < $today) {

I feel like I am not doing this in the most accepted way, but my brain hurts from too much data and I was hoping someone could give me a pointer as to the 'correct'approach.

Assuming you only care about the Date part, and not the time part, as in 2016-01-01 14:00:00 and 2016-01-01 15:00:00 would be counted as the same day and not the past, you can use the following:

$dateFromDatabase = new DateTime('2016-05-23 17:00:00'); // $rec[0] in your case
$current = new DateTime();

$difference = $current->diff($dateFromDatabase);

if ($difference->format('%R') === '-') {
    echo 'Date is in the past';
}

ideone can be found here

Any issues let me know.

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