2013-04-03 158 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