2016-05-13 85 views
2

我有一個日期,我收到MS格式的JSON日期。它看起來像這樣:如何將PHP DateTime對象轉換爲ISO字符串?

/Date(1365004652303)/ 

我可以這樣將它轉換爲PHP DateTime對象:

$timestamp = round(((int) $originalMSdate)/1000); 
$convertedDate = new DateTime(); 
$convertedDate->setTimestamp($timestamp); 

不過說到底,我需要它是在ISO 8601格式的字符串。我嘗試將其轉換爲ISO日期對象&,然後將其轉換爲strval()的字符串,但strval()在日期對象上不起作用。

我也試過

$dateString = date_format($convertedDate, 'YY-MM-DD H:i:s'); 

,但我需要它也包括時區信息,像這樣:2015-10-01T21:22:57.057Z 我沒有看到字符在DATE_FORMAT 。

我該如何做到這一點?

編輯:我應該澄清,我不打印結果字符串。我需要將它傳遞給接受字符串數據類型的數據庫中的字段。

+0

http://php.net/manual/en/function.date.php –

+1

[將字符串轉換爲日期時間]的可能重複(http://stackoverflow.com/questions/466345/converting-string-into-datetime ) – Sipty

+1

ISO 8601格式代碼'c';根據[PHP Documentation](http://nl3.php.net/manual/en/function.date.php) –

回答

1

請嘗試下面的代碼

<?php 
// input 
$time = microtime(true); 
// Determining the microsecond fraction 
$microSeconds = sprintf("%06d", ($time - floor($time)) * 1000000); 
// Creating DT object 
$tz = new DateTimeZone("Etc/UTC"); 
$dt = new DateTime(date('Y-m-d H:i:s.'. $microSeconds, $time), $tz); 
$iso8601Date = sprintf(
    "%s%03d%s", 
    $dt->format("Y-m-d\TH:i:s."), 
    floor($dt->format("u")/1000), 
    $dt->format("O") 
); 
// Formatting according to ISO 8601-extended 
var_dump(
    $iso8601Date 
); 
0

這工作:

$timestamp = round(((int) $originalMSdate)/1000); 
$dateString = date('c', $timestamp); 

格式不完全一樣。它的格式如下:

2016-04-25T14:27:00-05:00,而不是 2016-04-25T14:27:00.057Z

,但它足夠接近,我可以做一些操縱得到我需要的東西。