如何通过json和twig将DateTime对象传递给javascript日期对象

时间:2017-08-17 04:28:43

标签: javascript php json datetime twig

例如,我的对象在php中有DateTime个对象。

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效果很好,但无法将DateTime转换为javascript对象。

有什么好的解决方案吗?

1 个答案:

答案 0 :(得分: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)
相关问题