简体   繁体   中英

PHP - Check date is in the past but exclude todays date

I'm using the following function to check whether the date is in the past, but I want to exclude today's date from it as it returns true for today's date also.

For example, if I pass today's date 2018-03-15, it returns true when it shouldn't.

function is_date_in_past($date):bool
{
   return !empty($date) && (strtotime($date) < time());
}

Can anybody please help me with this, that how to exclude today's date from being recognised as past date?

Thanks in advance.

Use DateTime objects. They are easier to use than the old date & time functions and the code is more clear.

function is_date_in_past($date) {
    return new DateTime($date) < new DateTime("today");
}

If you'd like to use old date/time functions, you can do like that:

 function is_date_in_past(string $date) :bool
 {
     return !empty($date) && strtotime($date) < strtotime(date('Y-m-d'));
 }

but better to consider to use https://stackoverflow.com/a/49305230/9254020 variant

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