2011-03-11 80 views
1

我想在PHP中做一些基本的日期和時間戳操作,並且得到了意想不到的結果。我試圖在現有時間戳$startDate的月份(即日期的上午12:00點的時間戳)獲得時間戳。但是,它也在更改日期,如下面的代碼所示。php日期()函數產生意想不到的輸出

$startDateString = date("Y-M-j", $startDate); 
$startDateTimestamp = strtotime($startDateString); 
echo "$startDate == $startDateTimestamp ?<br>"; 
echo date("Y-M-j", $startDate)." == ".date("Y-M-j", $startDateTimestamp)." ?<br>"; 

這給了我下面的輸出:

1299299589 == 1298952000 ? 
2011-Mar-4 == 2011-Feb-28 ? 

雖然我不希望時間戳是相同的(如$startDate不一定在12:00 AM),我不能看日曆日期是不一樣的。我究竟做錯了什麼?

+0

您可能要參考[通過的strtotime支持的格式(http://us3.php.net/manual/en/datetime.formats.date.php),其中你將無法找到YMJ 。 – Charles 2011-03-11 04:54:32

回答

1

我通常用「Y-M-d」格式相似的任務和工作原理:

$startDateString = date("Y-m-d", $startDate); 
$startDateTimestamp = strtotime($startDateString); 
echo "$startDate == $startDateTimestamp ?<br>"; 
echo date("Y-m-d", $startDate)." == ".date("Y-m-d", $startDateTimestamp)." ?<br>"; 
2

strtotime文檔:

日期/時間字符串。有效格式在Date and Time Formats中解釋。

至於你正試圖解決的問題,你可以通過其他的東西,像relative formats

strtotime('midnight', $startDate); 

舉個例子,來呼應當前時間午夜(你也可以使用如果今天午夜是混亂):

echo date('Y-m-d H:i:s', strtotime('midnight')); 

兩個「今天」和「午夜」

時間設置爲00:00:00

當然我是的粉絲對象。

$date = new DateTime($startDate); 
$date->modify('midnight'); 
echo $date->format('Y-m-d H:i:s'); 
+0

這也很有幫助。如果我只能選擇兩個正確的答案! – jonmorgan 2011-03-11 05:10:38