-1

In php i want to compare two dates of format m-d-Y

so i tried following code

$strdte=trim($_REQUEST['stdate']);
$enddte=trim($_REQUEST['enddate']);


$today_time = $strdte;
$expire_time = $enddte;

if ($expire_time < $today_time) 
{
print '<script type="text/javascript">';print 'window.onload = function(){';
print 'alert("You cannot have end date before startdate")';
print '};';print '</script>';  
}

but problem is it sometimes work and sometime doesn't.Could anyone tell me what was the reason for this problem?

Thanks in advance.

krishna kumar
  • 153
  • 1
  • 6
  • 14
  • What is the format of stdate and enddate? You are doing string comparisons and not date comparisons. Format those strings to date and then compare. – Vaibhav Desai Apr 03 '13 at 08:35
  • possible duplicate of [Comparing two dates](http://stackoverflow.com/questions/3847736/comparing-two-dates) – deceze Apr 03 '13 at 08:36

2 Answers2

0

check date format if it is string format like '04-03-2013' then it won't be compared directly. You need to convert it to strtotime(time foramt) which will give you second string and then you can compare.

strtotime($expire_time) < strtotime($today_time)
mukund
  • 2,253
  • 1
  • 18
  • 31
0

I would turn your dates in a DateTime object then use the timestamp of the date tu make the comparaison. Date comparaison with string isn't a good idea. that would look like similiar to:

$start = DateTime($format,$_REQUEST['stdate']);
$end = DateTime($format,$_REQUEST['enddate']);

if ($end->getTimestamp() < $start->getTimestamp())
{
     print '<script type="text/javascript">';print 'window.onload = function(){';
     print 'alert("You cannot have end date before startdate")';
     print '};';print '</script>';  
}
FernCoder
  • 33
  • 1
  • 5
  • It depend of the format you are getting in your $_REQUEST. For example DateTime format is `"Y-m-d H:i:s"` for a date like "2013-04-03 15:04:00" which would be a mysql datetime format. You got some constante to help you on the DateTime man page and all the possibilities here [link](http://www.php.net/manual/fr/datetime.createfromformat.php) – FernCoder Apr 03 '13 at 13:06