How do I format a Microsoft JSON date?

后端 未结 30 3188
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 04:48

I\'m taking my first crack at Ajax with jQuery. I\'m getting my data onto my page, but I\'m having some trouble with the JSON data that is returned for Date data types. Basi

30条回答
  •  爱一瞬间的悲伤
    2020-11-21 04:54

    The original example:

    /Date(1224043200000)/  
    

    does not reflect the formatting used by WCF when sending dates via WCF REST using the built-in JSON serialization. (at least on .NET 3.5, SP1)

    I found the answer here helpful, but a slight edit to the regex is required, as it appears that the timezone GMT offset is being appended onto the number returned (since 1970) in WCF JSON.

    In a WCF service I have:

    [OperationContract]
    [WebInvoke(
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest
        )]
    ApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );
    

    ApptVisitLinkInfo is defined simply:

    public class ApptVisitLinkInfo {
        string Field1 { get; set; }
        DateTime Field2 { get; set; }
        ...
    }
    

    When "Field2" is returned as Json from the service the value is:

    /Date(1224043200000-0600)/
    

    Notice the timezone offset included as part of the value.

    The modified regex:

    /\/Date\((.*?)\)\//gi
    

    It's slightly more eager and grabs everything between the parens, not just the first number. The resulting time sinze 1970, plus timezone offset can all be fed into the eval to get a date object.

    The resulting line of JavaScript for the replace is:

    replace(/\/Date\((.*?)\)\//gi, "new Date($1)");
    

提交回复
热议问题