开发者

How to create a JavaScript date object from a JSON store?

I have following JSON respon开发者_JAVA百科se created by Doctrine 2 as a datetime entity in server-side and encoded as JSON by zend framework`s Zend_Json::encode($stores) method:

{
"birthdate":
{"date":"2011-08-19 00:00:00","timezone_type":3,"timezone":"Europe\/Berlin"}
}

I need to create a new Date() using this JSON for my Extjs data grid but I can't figure out how to manipulate JSON response. Assuming I have a JSON store and I can access to birthdate object, new Date(birthdate.date) gives "Date {Invalid Date}".new Date("date":"2011-08-19 00:00:00") gives the same error but new Date("date":"2011-08-19") works fine. Please advice me on how to create a date object from my JSON store.


You can parse the date using the following code

Date.parseDate("2011-08-19 00:00:00", "Y-m-d h:i:s");

API Doc

As per ExtJS 4.0 the method is changed as parse

Ext.Date.parse("2011-08-19 00:00:00", "Y-m-d h:i:s")

API Doc


That string isn't something that the Date constructor or Date.parse can understand. It can, however, understand the "YY-MM-DD" portion, though, so if that's enough granularity, you can do this:

var data = {
    "birthdate": {
        "date": "2011-08-19 00:00:00",
        "timezone_type": 3,
        "timezone":"Europe\/Berlin"
    }
};
// just parse the 'YY-MM-DD' part
new Date(data.birthdate.date.split(' ')[0]);


Edit: when I say that format can't be parsed, I mean in a cross-browser way. The latest Chrome, for example, understands the string just fine, whereas the latest FF does not. The 'YY-MM-DD' portion should be plenty cross-browser though (be sure to test and verify that though, obviously).


Have you try Date.parse ? https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse

If it is not parsed, you'll have to reformat the string format.


You have to parse your string to get a Date object (see here):

var yourDate = Date.parse("2011-08-19 00:00:00");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜