日期比较不起作用


date comparison not working

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

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

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

strtotime($expire_time) < strtotime($today_time)

我会将日期转换为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>';  
}