php if statement to check if current datetime is between 2 datetime columns

16,960

Solution 1

Use DateTime.

$now = new DateTime("now");
$PostQopen = new DateTime($rows['PostQopen']);
$PostQClose = new DateTime($rows['PostQClose']);

if($PostQopen >= $now && $PostQClose <=$now){
 // do ur stuff
}

Solution 2

Remove single quotes from $now and use strtotime(). Still without strtotime(), the code will work since you can compare time if it is in datetime format.

if(strtotime($rows['PostQopen']) >= strtotime($now) && strtotime($rows['PostQClose']) < strtotime($now) )
{
   echo "TRUE";
} 
else
{ 
   echo "FALSE";
}

Solution 3

$now = date('Y-m-d H:i:s');

if(strtotime($rows['PostQopen']) >= strtotime('$now') && strtotime($rows['PostQClose']) < strtotime('$now') ){

echo "TRUE";

} else { 

echo "FALSE";

};

Check if this works, strtotime converts given time into millisecond format, It should work

Solution 4

Function to find out between using DateTime is here:

function dateIsBetween($from, $to, $date="now") {
    $date = new \DateTime($date);
    $from= new \DateTime($from);
    $to = new \DateTime($to);
    if ($date >= $from && $date <= $to) {
        return true;
    }
    return false;
}

Using the function

dateIsBetween('2016-02-24', '2016-02-26', '2016-02-25'); //would return true
dateIsBetween('2016-02-24', '2016-02-26', 'now'); //would return true if the current date would be between specified to, from
dateIsBetween('2016-02-24', '2016-02-26'); //would return true if the current date would be between specified to, from
Share:
16,960

Related videos on Youtube

Craig Martin
Author by

Craig Martin

Updated on September 15, 2022

Comments

  • Craig Martin
    Craig Martin over 1 year

    PostQopen and PostQClose are datetime columns. I need a php if statement to check if the current datetime is between the PostQopen and PostQClose columns.

    $now = date('Y-m-d H:i:s');
    
    if($rows['PostQopen'] >= '$now' && $rows['PostQClose'] < '$now' ){
    
    echo "TRUE";
    
    } else { 
    
    echo "FALSE";
    
    };
    
    • Ashley
      Ashley about 10 years
      You don't need single quotes around the '$now' - try removing it and seeing if that fixes the problem.
  • Craig Martin
    Craig Martin about 10 years
    THIS WORKED FOR ME. $now = date('Y-m-d H:i:s'); $PostQopen = $rows['PostQopen']; $PostQClose = $rows['PostQClose']; if($now >= $PostQopen && $now < $PostQClose){ echo "TRUE"; };
  • Abhik Chakraborty
    Abhik Chakraborty about 10 years
    well u should avoid using strtotime() and use DateTime instead since strtotime() has many limitations and does not work in many cases.
  • Imran Zahoor
    Imran Zahoor over 7 years
    The above solution is not between it's actually not between.