PHP check if date between two dates
Edit: use
<=
or>=
to count today's date.
This is the right answer for your code. Just use the strtotime() php function.
$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today!
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
echo "is between";
}else{
echo "NO GO!";
}
You cannot compare date-strings. It is good habit to use PHP's DateTime
object instead:
$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today!
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd = new DateTime('2015-01-01');
if (
$paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() &&
$paymentDate->getTimestamp() < $contractDateEnd->getTimestamp()){
echo "is between";
}else{
echo "NO GO!";
}
If hours matter:
$paymentDate = strtotime(date("Y-m-d H:i:s"));
$contractDateBegin = strtotime("2014-01-22 12:42:00");
$contractDateEnd = strtotime("2014-01-22 12:50:00");
if($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd) {
echo "is between";
} else {
echo "NO GO!";
}
Based on luttken's answer. Thought I'd add my twist :)
function dateIsInBetween(\DateTime $from, \DateTime $to, \DateTime $subject)
{
return $subject->getTimestamp() > $from->getTimestamp() && $subject->getTimestamp() < $to->getTimestamp() ? true : false;
}
$paymentDate = new \DateTime('now');
$contractDateBegin = new \DateTime('01/01/2001');
$contractDateEnd = new \DateTime('01/01/2016');
echo dateIsInBetween($contractDateBegin, $contractDateEnd, $paymentDate) ? "is between" : "NO GO!";