How to convert JavascriptSerializer serialized DateTime string to Javascript Date object

后端 未结 4 2006
别那么骄傲
别那么骄傲 2021-02-07 11:35

After serializing an object with DateTime field with JavaScriptSerializer, I see that the DateTime field looks like this:

         


        
4条回答
  •  情书的邮戳
    2021-02-07 11:43

    UPDATE: This answer may not be appropriate in all cases. See JD's answer for an elegant solution that is likely better.

    You could just "fix" the output from JavaScriptSerializer on the .Net side of things:

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(this);
    json = Regex.Replace(json,@"\""\\/Date\((-?\d+)\)\\/\""","new Date($1)");
    return json;
    

    This would change

    EffectiveFrom: "/Date(1355496152000)/"
    

    to

    EffectiveFrom: new Date(1355496152000)
    

    Which is directly consumable by Javascript

    EDIT: update to accommodate negative dates

    EDIT: Here is the Regex line for VB folks:

    json = Regex.Replace(json, """\\/Date\((-?\d+)\)\\/""", "new Date($1)")
    

    UPDATE 2016.11.20: With a lot more datetime handling in javascript/json behind me, I would suggest changing the regex to something as simple as

    json = Regex.Replace(json,@"\""\\/Date\((-?\d+)\)\\/\""","$1");
    

    The resulting value is valid JSON, and can be converted to a Date object on the javascript side.

    It is also worth noting that moment.js (http://momentjs.com/docs/#/parsing/) handles this format happily enough.

    moment("/Date(1198908717056-0700)/");
    

提交回复
热议问题