2011-09-15 106 views
2

我有一個簡單的事情,我試圖解決。爲什麼這個簡單的陳述如此簡單?

我有一個日期存儲在一個表中,我將它與PHP生成的日期進行比較。

即:

if($row['start_date'] < date("Y-m-d")) { 

    // table stored date larger than php date 
    echo 'hi'; 

} else { 

    // php date larger than table stored date 
    echo 'bye'; 

} 

這似乎確定我,但

if $row['start_date'] === '2011-09-13' AND date("Y-m-d") === '2011-09-15'. 

我結束了:

hi 

這可能是那些黃昏時刻,我想到的一個左邊是對的,大於符號實際上是小於。所以請幫助我 - 爲什麼這不起作用?

+1

我建議['strtotime()'](http://php.net/manual/en/function.strtotime.php)。 –

+1

嗯,但不是''2011-09-13'<'2011-09-15''是真的嗎? PHP中的 – NullUserException

+0

與lexigraphically使用'<?可能最好轉換爲某種數字類型(unix timestamp?)並進行比較。 –

回答

2

如果$row['start_date'] = '2011-09-13'date("Y-m-d") = '2011-09-15',那麼你的PHP日期是大於行的日期,因此if是真的,畢竟'2011-09-13'是「小(<)」比'2011-09-15'。翻轉你的<>,你會沒事的。

if($row['start_date'] > date("Y-m-d")) { 

    // table stored date larger than php date 
    echo 'hi'; 

} else { 

    // php date larger than table stored date 
    echo 'bye'; 

} 
+0

啊..所以我瘋了 – willdanceforfun

4

比較,你必須使用strtotime()$row['start_date']日期和time()

if(strtotime($row['start_date']) < time()) 
+0

你不必「使用'strtotime()' – NullUserException

1

使用strtotime()轉換的字符串Unix時間戳然後進行比較。 或使用DateTime對象。

0

我不確定比較日期作爲字符串的有效性,使用DateTimestrtotime並比較時間戳可能是更健壯的選項,但使用此日期格式它應該作爲字符串工作。

除此之外,你的邏輯看起來像書面的(如果不是按照預期的)工作。 「... 13」小於「... 15」,因此if將評估爲true,將打印「hi」。

從內嵌評論來看,它似乎實際上可能是您所說的那些暮色時刻之一。

相關問題