How to convert JavascriptSerializer serialized DateTime string to Javascript Date object

后端 未结 4 2007
别那么骄傲
别那么骄傲 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:47

    This is a bit of a hack, but the above seemed inelegant for what I'm trying to achieve, so in the object definition I'm serializing, I did this:

            /// Date of the record retention event or document date.
            /// 
            public string DateOfRetentionEvent;
            [ScriptIgnore]
            public DateTime RetentionEventDate 
            {
                get
                {
                    return _retentionEventDate;
                }
                set
                {
                    _retentionEventDate = value;
                    DateOfRetentionEvent = value.ToShortDateString();
                }
            }
    

    The point being that, at least in my use case (deserialization never happens), the JSON doesn't really care what C# is doing with the date value. Adding [ScriptIgnore] to the DateTime value and giving an alternative view for the parser to output should do the trick. It does in my case:

    {
        "DateToDispose": "1/1/2020",
        "DateOfRetentionEvent": "10/1/2014",
        "FullRetentionCode": "NR+5",
        "RetentionEvent": "NR",
        "RetentionPeriod": 5
    }
    

提交回复
热议问题