1

Less than operator not working while comparing date

   $today="27-02-2015";
$end="24-06-2015";
if($end < $today){
echo "yes";

}else{
echo "no";
}

4 Answers4

4

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";
}
Benz
  • 2,317
  • 12
  • 19
2

change the string to format "2015-02-27" - then year is first, then month and you can compare like numbers

n-dru
  • 9,285
  • 2
  • 29
  • 42
0

It should be

$today=strtotime("27-02-2015");
$end=strtotime("24-06-2015");
if($end < $today){
 echo "yes";

}else{
echo "no";
}
Mihir Bhatt
  • 3,019
  • 2
  • 37
  • 41
0

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.

collapsar
  • 17,010
  • 4
  • 35
  • 61