Prevent Json.NET 4.5 from appending timezone offset when using MicrosoftDateFormat

前端 未结 2 519
攒了一身酷
攒了一身酷 2021-02-12 13:44

Short of a custom DateTimeConverterBase implementation, is there some way to keep Json.NET 4.5+, when set to use DateFormatHandling.MicrosoftDateFormat

相关标签:
2条回答
  • 2021-02-12 14:14

    It seems to work just fine for me, see below. My JSON.NET assembly says it's version "4.5.0.0".

    JsonSerializerSettings customJsonSettings = new JsonSerializerSettings()
    {
        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
        DateTimeZoneHandling = DateTimeZoneHandling.Utc
    };
    string result = JsonConvert.SerializeObject(DateTime.Now, customJsonSettings);
    Console.WriteLine(result); // "\/Date(1344249339881)\/"
    

    Perhaps it was a bug that has been fixed?

    Explicitly creating a date:

    var x = new { thedate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Local) };
    
    Console.WriteLine(JsonConvert.SerializeObject(x,
        new JsonSerializerSettings() {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
        }));
    // {"thedate":"\/Date(1234652400000+0100)\/"}
    
    Console.WriteLine(JsonConvert.SerializeObject(x,
        new JsonSerializerSettings() {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
            DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc
        }));
    // {"thedate":"\/Date(1234652400000)\/"}
    
    Console.WriteLine(JsonConvert.SerializeObject(x,
        new JsonSerializerSettings() {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
            DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local
        }));
    // {"thedate":"\/Date(1234652400000+0100)\/"}
    
    0 讨论(0)
  • 2021-02-12 14:26

    I found a solution to remove timezone offset from DateTime for latest version 9.0.0:

    var time = DateTime.Now;
    
    Console.WriteLine(JsonConvert.SerializeObject(time, new JsonSerializerSettings()
    {
        DateFormatHandling = DateFormatHandling.IsoDateFormat,
        DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Unspecified
    }));
    
    //"{"thedate": "2016-12-15T09:20:00.9375403"};
    
    0 讨论(0)
提交回复
热议问题