I'm trying to display a datetime from my MySQL database as an iso 8601 formated string with PHP but it's coming out wrong.
我試圖將我的MySQL數據庫中的datetime顯示為iso 8601格式的PHP字符串,但它出了問題。
17 Oct 2008 is coming out as: 1969-12-31T18:33:28-06:00 which is clearly not correct (the year should be 2008 not 1969)
2008年10月17日公布的日期為:1969-12- 31t18:33 - 33:28-06:00這顯然是不正確的(2008年應該是2008年而不是1969年)
This is the code I'm using:
這是我使用的代碼:
= date("c", $post[3]) ?>
$post[3] is the datetime (CURRENT_TIMESTAMP) from my MySQL database.
$post[3]是我的MySQL數據庫中的datetime (CURRENT_TIMESTAMP)。
Any ideas what's going wrong?
有什么問題嗎?
5 个解决方案
#1
64
The second argument of date is a UNIX timestamp, not a database timestamp string.
日期的第二個參數是UNIX時間戳,而不是數據庫時間戳字符串。
You need to convert your database timestamp with strtotime.
您需要使用strtotime轉換數據庫時間戳。
= date("c", strtotime($post[3])) ?>
#2
26
Using the DateTime class available in PHP version 5.2 it would be done like this:
使用PHP version 5.2中提供的DateTime類,可以這樣做:
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
看到它在行動
As of PHP 5.4 you can do this as a one-liner:
對於PHP 5.4,您可以使用一行代碼:
echo (new DateTime('17 Oct 2008'))->format('c');
#3
8
Procedural style :
echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Object oriented style :
$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 1 :
echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 2 :
echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00
Notes :
1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.
1)你也可以用“Y-m-d\TH:i:sP”來代替“c”。
2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :
2)您的輸入的默認時區是服務器的時區。如果希望輸入的時區不同,則需要顯式地設置時區。然而,這也將影響您的輸出:
echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00
3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :
3)如果您希望輸出的時區與輸入的時區不同,您可以顯式設置您的時區:
echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00
#4
6
For pre PHP 5:
PHP 5之前:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
#5
6
Here is the good function for pre PHP 5: I added GMT difference at the end, it's not hardcoded.
這是pre PHP 5的一個很好的函數:我在末尾添加了GMT差異,它不是硬編碼的。
function iso8601($time=false) {
if ($time === false) $time = time();
$date = date('Y-m-d\TH:i:sO', $time);
return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}