-3

I want to compare if given date is older then current date. Result of IF statement 'date is in the future' . Can someone tell me why PHP gives wrong result in IF statement?

Here is code that I am using

$date='17/06/2013';  
$currentDate = date("d/m/Y");

if(strtotime($date) < strtotime($currentDate)) {
echo 'date is in the past';
}
else{
 echo 'date is in the future';
}
user2496520
  • 881
  • 4
  • 13
  • 36

3 Answers3

4

Your date format is not valid. From the manual (emphasis mine):

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

If you're going to use that format you need to be explicit in telling PHP the format of that date. Use DateTime::createFromFormat() to disambiguate the date format. Also, DateTime objects are comparable which makes your code more readable (and they also handle timezones and daylight savings time which strtotime() does not do):

$date = DateTime::createFromFormat('d/m/Y', '17/06/2013');  
$currentDate = new DateTime();

if($date < $currentDate) {
echo 'date is in the past';
}
else{
 echo 'date is in the future';
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

xkcd
> xkcd

strtotime is failing to parse your date string. false is not less than itself, therefore date is "in the future".

Try using the correct way to write numeric dates ;)

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

try replacing(/) to (-) need to pass correct format to strtotime to detect correct date so correct way is to write date with -(dash)

$date=str_replace('/', '-', '17/06/2013');  
$currentDate = date("d-m-Y");
if(strtotime($date) < strtotime($currentDate)) {
  echo 'date is in the past';
}
else{
  echo 'date is in the future';
}
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44