看板 Farland
作者 標題 [程式] Convert serialzed JSON date string to a Javascript Date() object
時間 2012年02月10日 Fri. PM 05:23:56
出處:http://blog.sendreallybigfiles.com/2010/02/convert-serialzed-json-date-string-to.html
Convert serialzed JSON date string to a Javascript Date() object
When an DateTime object in C# is converted into a JSON serialized object for a web page, the format of the string looks like this in the JSON object:
/Date()/
See this for more details on why this format was chosen. This is all well and good, but how do you use that? A similar question and answer can be found here, but the solution posted there misses the possibility of a negative int.
To expand just a bit on the solution posted there, we'll account for negative numbers:
someDate = new Date(+jsonDate.replace(/\/Date\((-?\d+)\)\//gi, "$1"));
The three key things to note here are:
1. This method does not use eval(). eval can be a very dangerous thing to use since it will execute any javascript, so generally we try to avoid using it altogether. This is why we use JSON.parse, for example, instead of eval.
2. The "+" operator is a type converter in javascript that converts the string to an int.
3. The "-?" because the date value can, indeed, be a negative value (try 03/29/1938 for example).
Posted by Brent Bulla at Friday, February 26, 2010
--
※ 作者: Farland 時間: 2012-02-10 17:23:56
※ 編輯: Farland 時間: 2012-02-10 17:25:05
※ 看板: Farland 文章推薦值: 0 目前人氣: 0 累積人氣: 185
回列表(←)
分享