2013-04-03 149 views
-1

在PHP我想比较格式的两个日期m-d-Y日期比较不工作

,所以我尝试下面的代码

$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>'; 
} 

,但问题是,它有时工作和某个doesn't.Could谁能告诉我这个问题的原因是什么?

在此先感谢。

+0

什么是stdate和enddate的格式?你正在做字符串比较而不是日期比较。格式化这些字符串到日期然后比较。 –

+0

[比较两个日期]可能的重复(http://stackoverflow.com/questions/3847736/comparing-two-dates) – deceze

回答

0

检查日期格式,如果它是字符串格式如'04-03-2013'那么它不会被直接比较。你需要将它转换为strtotime(time foramt),它会给你第二个字符串,然后你可以比较。

strtotime($expire_time) < strtotime($today_time) 
0

我会变成你的日期在DateTime对象,然后使用日期恩的时间戳进行comparaison。与字符串的日期比较不是一个好主意。那看起来像类似于:

$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>'; 
} 
+0

我应该使用什么格式。 –

+0

它取决于您在$ _REQUEST中获得的格式。例如,日期时间格式是'“Y-m-d H:i:s”',用于像“2013-04-03 15:04:00”这样的日期,这将是一个MySQL日期时间格式。你有一些常量来帮助你在DateTime手册页和所有可能性[链接](http://www.php.net/manual/fr/datetime.createfromformat.php) – FernCoder