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
Related videos on Youtube
Author by
Craig Martin
Updated on September 15, 2022Comments
-
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 about 10 yearsYou don't need single quotes around the '$now' - try removing it and seeing if that fixes the problem.
-
-
Craig Martin about 10 yearsTHIS 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 about 10 yearswell u should avoid using strtotime() and use DateTime instead since strtotime() has many limitations and does not work in many cases.
-
Imran Zahoor over 7 yearsThe above solution is not between it's actually not between.