I got this code from Stackoverflow and changed it slightly to work with today's date.
I want to check if today fits between two dates. But this is not working. What am I missing?
$paymentDate = date('d/m/Y'); echo $paymentDate; // echos today! $contractDateBegin = date('d/m/Y', '01/01/2001'); $contractDateEnd = date('d/m/Y', '01/01/2015'); if ($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd) { echo "is between"; } else { echo "NO GO!"; }
To check if a date is between two dates:Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.
The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With