0

I'm using NewtonJson.NET in order to de/serialize my classes to json format.

I don't know why, but it serializes DateTime values like this example: 2015-07-23T10:39:31.0017599+02:00.

My server understands ISO8601 format: yyyy-MM-dd'T'HH:mm:ss.SSSZ.

I'm figuring out the problem is on milliseconds SSS part.

How could I change it?

I'd need to set this configuration as a globally form, so, no in each field for example. I'd like NewtonJson always serialize DateTime values as ISO8601 format.

Thanks for all.

Jordi
  • 20,868
  • 39
  • 149
  • 333

2 Answers2

2

ISO 8601 is default for Json.NET since 4.5 version. Both what you get and what you want is ISO 8601, in latter case Z means that time is in UTC:

// This is equal to 2015-07-23T12:22:17.7902881+03:00
JsonConvert.SerializeObject(DateTime.Now);

// This is equal to 2015-07-23T09:22:18.0585302Z
JsonConvert.SerializeObject(DateTime.UtcNow);

To tell Json.NET to interpret DateTime as UTC you can use global settings:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

Or local settings:

Console.WriteLine(JsonConvert.SerializeObject(DateTime.Now, new JsonSerializerSettings
{
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
}));
Community
  • 1
  • 1
Leonid Vasilev
  • 11,910
  • 4
  • 36
  • 50
  • Thanks! That's it! Am I be able to set .Net standard DateTime as UTC? Or I always I need to specify it programatically? – Jordi Jul 23 '15 at 18:14
1

You can specify the format converter for example by annotating the property:

[JsonProperty(ItemConverterType = typeof(CustomDateTimeConverter))]
public DateTime? DateTime1;

class CustomDateTimeConverter : IsoDateTimeConverter
{
    public CustomDateTimeConverter()
    {
        DateTimeFormat = "MM.dd.yyyy";//specify your format
    }
}
nyconing
  • 1,092
  • 1
  • 10
  • 33
Vojtech B
  • 2,837
  • 7
  • 31
  • 59