Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if date between two dates

Tags:

date

php

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!";   } 
like image 837
Papa De Beau Avatar asked Sep 28 '13 18:09

Papa De Beau


People also ask

How do you know if a date is between two dates?

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.

How can I get days between two dates in php?

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.


2 Answers

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!";   } 
like image 177
g.m.ashaduzzaman Avatar answered Sep 17 '22 13:09

g.m.ashaduzzaman


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!";   } 
like image 43
luttkens Avatar answered Sep 19 '22 13:09

luttkens