2017-07-24 38 views
2

我寫這段代碼其中之一:如果我提供$ customDate像PHP:兩個同日聲明,但星期是錯誤的

if(!is_null($customDate)){ 
    $referenceDate = strtotime($customDate); 
    $toDay = date("N", $referenceDate); 
    echo("/".$referenceDate."/".$toDay."/"); 
} 
else{ 
    $referenceDate = strtotime(date("d:m:y")); 
    $toDay = date("N"); 
    echo("/".$referenceDate."/".$toDay."/"); 
} 

函數名(「24: 7" 時17分);

它打印出這一點:

/2分之1500941237/

一個日期戳(我認爲)和2周的天 - 週二。

如果我不提供$ customDate和呼叫功能:

函數名();

我得到這個:

/1分之1500941237/

這又是 - 郵戳(我認爲)和1周的一天 - 週一。

第二個是正確的,它是24號,它是星期一。

我對PHP很新穎,所以我幾乎100%確定在操作日期時有一些細微差別,但我不確定它是什麼。

兩張相同的日期戳怎麼能產生不同的星期幾?

使用默認配置在Windows 10上的WAMP服務器上運行它。

全功能:

function nextDate($customDate=null){ 

    $referenceDate; 
    $toDay; 


    if(!is_null($customDate)){ 
     $referenceDate = strtotime($customDate); 
     $toDay = date("N", $referenceDate); 
     echo("/".$referenceDate."/".$toDay."/"); 
    } 
    else{ 
     $referenceDate = strtotime(date("d:m:y")); 
     $toDay = date("N"); 
     echo("/".$referenceDate."/".$toDay."/"); 
    } 

} 

nextDate( 「24:07:17」); - >給出了錯誤的結果,它說24日是星期二。

nextDate(); - >給出正確的結果,它說24日是星期一。

+0

你能告訴我們處理日期後的代碼嗎? – GrumpyCrouton

+0

@GrumpyCrouton沒有日期處理,我只是從函數外部調用nextDate()。 – iAmTheGuy96

+0

我已經運行你的代碼在線編輯器,我還沒有看到任何問題都有相同的結果顯示在這兩種情況。 http://www.writephponline.com/ – rowmoin

回答

4

這是因爲24:07:17是無效的日期格式,PHP認爲這是一個時間,所以「今天24:07:17」

echo date("Y-m-d H:i:s", strtotime("24:07:17")); 
// outputs 2017-07-25 00:07:17 

使用有效日期格式,或將其轉換爲東西strtotime將能正確理解:

list($d,$m,$y) = explode(":", "24:07:17"); 
$referenceDate = strtotime("20{$y}-{$m}-{$d}"); 
+0

所以這是一個分隔符「:」問題或日|月|年份序列? – iAmTheGuy96

+0

@ iAmTheGuy96兩者。 'date(「Y-m-d」,strtotime(「01-03-17」));'是2001年3月。我們在計算機中使用Y-M-D的原因是https://en.wikipedia。org/wiki/ISO_8601 – Peter

+0

謝謝,現在就解釋它。 它現在完美運作。不知道D:M:Y和Y-m-d之間有如此大的差異 – iAmTheGuy96