简体   繁体   中英

How to pass DateTime object to javascript date object via json and twig

For example, I have object which has DateTime object in php.

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"
        ));

parse the object like this.

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"};

in this way text and boolean works well but can't convert DateTime to javascript object.

Is there any good solution??

You should be able to use your datetime string from JSON to instantiate a Date object like so:

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

This can then be used like so, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM