简体   繁体   中英

How can I determine if a date is between two dates in PHP?

I need know if a $paymentDate (31/12/2010) is valid between $contractDateBegin (01/01/2001) and $contractDateEnd (01/01/2012)

dd/mm/yyyy FORMAT !

As of PHP 5.3:

$paymentDate = DateTime::createFromFormat('d/m/Y', '31/12/2010');
$contractDateBegin = DateTime::createFromFormat('d/m/Y', '01/01/2001');
$contractDateEnd = DateTime::createFromFormat('d/m/Y', '01/01/2012');

if ($paymentDate >= $contractDateBegin && $paymentDate <= $contractDateEnd)
{
  echo "is between\n";
}

You may need to adjust the use of <= to < depending on whether or not the dates are exclusive.

if they are formatted as YYYYMMDD you can check if $paymentDate > $contractDateBegin and $paymentDate < $contractDateEnd

This works with any numeric format that has the larger formats first. If you have american dates for example MM/DD/YYYY, it doesn't work.

$test = strtotime($paymentDate);
if ($test >= strtotime($contractDateBegin) && $test <= strtotime($contractDateEnd))

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