How to get JSON.NET to serialize date/time to ISO 8601?

只愿长相守 提交于 2019-12-03 05:46:48

The format you are getting is ISO 8601 format (read the section on Times and Time Zone Designators in Wikipedia), it's just that your dates are apparently not adjusted to UTC time, so you are getting a timezone offset appended to the date rather than the Z Zulu timezone indicator.

The IsoDateTimeConverter has settings you can use to customize its output. You can make it automatically adjust dates to UTC by setting DateTimeStyles to AdjustToUniversal. You can also customize the output format to omit the fractional seconds if you don't want them. By default, the converter does not adjust to UTC time and includes as many decimals of precision as there are available for the seconds.

Try this:

IsoDateTimeConverter converter = new IsoDateTimeConverter
{
    DateTimeStyles = DateTimeStyles.AdjustToUniversal,
    DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK"
};

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(converter);

If your dates are already UTC, but the DateTimeKind on them is not set to Utc like it should be (e.g. it is Unspecified), then ideally you should fix your code so that this indicator is set correctly prior to serializing. However, if you can't (or don't want to) do that, you can work around it by changing the converter settings to always include the Z indicator in the date format (instead of using the K specifier which looks at the DateTimeKind on the date) and removing the AdjustToUniversal directive.

IsoDateTimeConverter converter = new IsoDateTimeConverter
{
    DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
};

Adding to @Brian Rogers' answer, for ASP Core, add in Startup.cs:

services.AddMvc()
  .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
  .AddJsonOptions(options =>
    options.SerializerSettings.Converters.Add(new IsoDateTimeConverter
    {
      DateTimeStyles = DateTimeStyles.AdjustToUniversal
    }));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!