日期比较不起作用

时间:2013-04-03 08:32:33

标签: php validation date

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

但问题是它有时是有效的,有时也不行。有谁能告诉我这个问题的原因是什么?

提前致谢。

2 个答案:

答案 0 :(得分:0)

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

strtotime($expire_time) < strtotime($today_time)

答案 1 :(得分:0)

我会在DateTime对象中转换您的日期,然后使用日期时间戳进行比较。与字符串的日期比较不是一个好主意。看起来很像:

$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>';  
}
相关问题