How to trim in JSON the miliseconds in DateTime serialization

痴心易碎 提交于 2020-01-07 07:43:35

问题


I have a WEB API 2 call, with Entity Framework. If I update a DateTime column from my entity that I read from the database with DateTime.Now, and I serialize it to the client, the column with DateTime that I received from the database has 3 numbers for the milliseconds, but the column with DateTime that I updated in the C# code has 6 digits. Below is the C# code in my controller:

[Route("{id:long}/updatedatetime", Name = "UpdateDateTimeByID")]
[HttpPost]
[ResponseType(typeof(ClGroup))]
public async Task<IHttpActionResult> UpdateDateTimeByID(int id)
{
        ClGroup clGroup = await db.ClGroups.FindAsync(id);
        if (clGroup == null)
        {
        return NotFound();
        }
        clGroup.DtUpdate = DateTime.Now;

        await db.SaveChangesAsync();
        var groupReturn = mapper.Map<ClGroupModel>(clGroup);
        return Ok(groupReturn);
}

Below is the JSON that is serialized back to the client

{
  "CdGroup": 1,
  "NmGroup": "Grupo 1",
  "DcGroup": "Primeiro Grupo",
  "DtInsert": "2016-07-03T22:18:52.257",
  "DtUpdate": "2016-07-12T13:31:08.2882558",
  "IdStatus": true
}

Is there a way so that the DtUpdate is serialized with 3 digits as well? I changed the formatter with the configuration below:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Unspecified;
json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;

Thanks


回答1:


Use an IsoDateTimeConverter and set the DateFormatString property on it like this:

var dateConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter 
{ 
    DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'" 
};
json.SerializerSettings.Converters.Add(dateConverter);

The lowercase fff ensures the milliseconds portion is always exactly 3 digits long. In contrast, the default format uses uppercase FFFFFFF for the milliseconds, which includes up to seven digits of precision, but omits trailing zeros. This is why you are seeing varying lengths for the milliseconds.

See Custom Date and Time Format Strings in the .NET Framework documentation for more info on custom date formats.



来源:https://stackoverflow.com/questions/38334607/how-to-trim-in-json-the-miliseconds-in-datetime-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!