Use JSON.NET to parse json date of format Date(epochTime-offset)

后端 未结 2 1978
既然无缘
既然无缘 2020-12-20 23:40

I am using Json.net 7.0.1 in C# to consume a rest API. The trouble is with the date format the API uses in its JSON response. It looks like this:

/Date(14453         


        
2条回答
  •  半阙折子戏
    2020-12-21 00:39

    The -hhmm indicates that a local time was serialized, not a UTC time. .NET, like many other platforms, recognizes the concept of time zones. In .NET, for example, the DateTime class has a property indicating what kind of date/time you're dealing with. You can explicitly construct date/times of different kinds. The debugger is terrible for not pointing this out, but you can see it with the following code.

    var dt1 = new DateTime(2015, 01, 01, 00, 00, 00); // defaults to DateTimeKind.Unspecified
    var dt2 = new DateTime(2015, 01, 01, 00, 00, 00, DateTimeKind.Local);
    var dt3 = new DateTime(2015, 01, 01, 00, 00, 00, DateTimeKind.Utc);
    var dt4 = new DateTime(2015, 01, 01, 00, 00, 00, DateTimeKind.Unspecified);
    Debug.WriteLine(dt1.Kind); // writes "Unspecified"
    Debug.WriteLine(dt2.Kind); // writes "Local"
    Debug.WriteLine(dt3.Kind); // writes "Utc"
    Debug.WriteLine(dt4.Kind); // writes "Unspecified"
    

    You can then see the effect the DateTimeKind has on the Json with the following

    // local time -- default datetime handling from JSON.NET
    {
        var dateTime = DateTime.Now;
        var jsonObject = new JObject {["dateTime"] = dateTime};
        var jsonString = jsonObject.ToString();
        Debug.WriteLine(jsonString); // uses "2015-10-19T18:13:53.4698565-04:00" form
    }
    // UTC time -- default datetime handling from JSON.NET
    {
        var dateTime = DateTime.Now.ToUniversalTime();
        var jsonObject = new JObject {["dateTime"] = dateTime };
        var jsonString = jsonObject.ToString();
        Debug.WriteLine(jsonString); // uses "2015-10-19T22:13:53.5166571Z" form
    }
    // local time -- Microsoft-like datetime handling from JSON.NET
    {
        var dateTime = DateTime.Now;
        var jsonObject = new JObject {["dateTime"] = dateTime };
        var jsonString = JsonConvert.SerializeObject(jsonObject, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
        Debug.WriteLine(jsonString); // uses "/Date(1445292833516-0400)/" format
    }
    // local time -- Microsoft-like datetime handling from JSON.NET
    {
        var dateTime = DateTime.Now.ToUniversalTime();
        var jsonObject = new JObject {["dateTime"] = dateTime };
        var jsonString = JsonConvert.SerializeObject(jsonObject, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
        Debug.WriteLine(jsonString); // uses "/Date(1445292833579)/" form
    }
    

提交回复
热议问题