问题描述
我有一个使用实体框架的WEB API 2调用.如果我使用DateTime.Now
从数据库读取的实体中更新了DateTime
列,并将其序列化到客户端,则我从数据库收到的具有DateTime
的列具有3个毫秒数,但是我在C#代码中更新的带有DateTime
的列有6位数字.下面是我的控制器中的C#代码:
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);
}
下面是序列化回客户端的JSON
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
}
有没有办法将DtUpdate
序列化为3位数字?我使用以下配置更改了格式化程序:
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;
谢谢
推荐答案
使用 IsoDateTimeConverter
并在其上设置DateFormatString
属性,如下所示:
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);
小写的fff
确保毫秒部分始终恰好是3位数字.相反,默认格式使用大写字母FFFFFFF
表示毫秒,包括最多7位精度,但省略了尾随零.这就是为什么您看到毫秒长度不同的原因.
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.
请参见自定义日期和时间格式字符串,以获取有关自定义日期格式的更多信息.
这篇关于如何在JSON中修剪DateTime序列化中的毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!