Reputation:
Less than operator not working while comparing date
$today="27-02-2015";
$end="24-06-2015";
if($end < $today){
echo "yes";
}else{
echo "no";
}
Upvotes: 1
Views: 78
Reputation: 17238
Build Date objects from string specified in the way your locale settings mandate and compute the differences on epoch millisecond:
$s_today = '02/27/2015';
$s_end = '06/24/2015';
date_default_timezone_set ( 'UTC' ); # required by strtotime. Actual value doesn't matter as you are interested in the date diff only
$today = strtotime($s_today);
$end = strtotime($s_end);
if ($end < $today) {
echo "less ( $s_today < $s_end )";
} else {
echo "more ( $s_today > $s_end )";
}
Note
@n-dru's approach is viable too. It depends which date specs your code fragment must cope with and if you wish to perform more computations on the dates. In the latter case I'd opt in favor of normalization to the epoch seconds. Otherwise it proabably isn't worth the hassle.
Upvotes: 0
Reputation: 2335
You are doing a string compare here, which does not tell you which date is later/earlier. You could change these dates into DateTime and compare them
$a = DateTime::createFromFormat('d-m-Y', '27-02-2015');
$b = DateTime::createFromFormat('d-m-Y', '24-06-2015');
if ($b < $a) {
echo " do something here";
}
Upvotes: 4
Reputation: 3155
It should be
$today=strtotime("27-02-2015");
$end=strtotime("24-06-2015");
if($end < $today){
echo "yes";
}else{
echo "no";
}
Upvotes: 0
Reputation: 9430
change the string to format "2015-02-27" - then year is first, then month and you can compare like numbers
Upvotes: 2