Pascal
Pascal

Reputation: 2984

How to trim in JSON the miliseconds in DateTime serialization

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

Upvotes: 0

Views: 2887

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129787

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.

Upvotes: 7

Related Questions