2017-08-17 76 views
0

例如,我有一個對象,它在php中有DateTime對象。如何通過json和樹枝將DateTime對象傳遞給javascript日期對象

in php

array_push($events, 
    array(
     "date" => new \DateTime('2017-08-01'), 
     "description" => "This is description of an event" 
    )); 
    array_push($events, 
     array(
     "date" => new \DateTime('2017-07-19'), 
     "description" => "Some longer\ntext can also\n be added" 
     )); 

解析這樣的對象。以這種方式

in twig

{% for var, value in events %} 
var {{var}} = {{ value|json_encode|raw }}; 
{% endfor %} 

output

var 0 = {"date":{"date":"2017-08-01 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Tokyo"},"description":"This is description of an event"}; 
var 1 = {"date":{"date":"2017-07-19 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Tokyo"},"description":"Some longer\ntext can also\n be added"}; 

textboolean作品很好,但不能轉換日期時間爲JavaScript對象。

有沒有什麼好的解決方案?

回答

1

您應該能夠使用從JSON你的時間字符串實例像Date對象,因此:

var d = new Date('2017-08-01 00:00:00.000000'); 

然後可以使用像這樣,例如:

alert(d.toString()); //Tue Aug 01 2017 00:00:00 GMT+0100 (GMT Summer Time) 
+0

感謝我發現那Date類的構造函數可以帶多種字符串。 – whitebear