I am experiencing an issue when comparing two dates in php.
The problem: When comparing 12:00 AM (midnight) to eg 10:00 AM (morning) the following code will not work properly. According to human logic 10:00 AM is later than 12:00 AM. But computers seem not to recognize that.
Is there any way to do this differently?
date_default_timezone_set('Europe/Athens');
$today = date("d-m-Y h:i:s A");
$today = date("d-m-Y h:i:s A",strtotime($today));
$max = date('d-m-Y h:i:s A', strtotime("31-12-2015 23:59:00"));
$min = date('d-m-Y h:i:s A', strtotime("14-12-2015 00:00:01"));
if (($today > $min) && ($today < $max)){
//do something
} else {
//something else done
}
Because date()
return String.
From the manual:
Return Values
Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.
Basically, what your code trying to do is something like this:
if("31-12-2015 23:59:00 PM" < "14-12-2015 00:00:01 AM") {
.......
}
So, PHP will ignore the "AM" or "PM" string, and just compare the numeric value.
EDIT: From comparison operator manual:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
So, because PHP convert their value again, then your code is comparing a different value entirely.
Is there any way to do this differently?
Just compare from the strtotime
value.
$today = strtotime("now");
$max = strtotime("31-12-2015 23:59:00");
$min = strtotime("14-12-2015 00:00:01");
if (($today > $min) && ($today < $max)){
//do something
}else{
//something else done
}
and later format your value again using date
to AM/PM format (if needed).
Try like this..
date_default_timezone_set('Europe/Athens');
$today = date("d-m-Y h:i:s A");
$max = date('d-m-Y h:i:s A', strtotime("31-12-2015 23:59:00"));
$min = date('d-m-Y h:i:s A', strtotime("14-12-2015 00:00:01"));
if ((strtotime($today) > strtotime($min)) && (strtotime($today) < strtotime($max))){
//do something
}else{
//something else done
For example:
if (strtotime("12:00 AM")>strtotime("10:00 AM")){
echo "do something";
}else{
echo "something else done";
}
//output "something else done";
You can use date_create()
& date_diff()
PHP inbuilt functions, to compare two dates and in your scenario it will help you.
$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff = date_diff($date1,$date2);
echo $diff->format("%R%a days");