如何强制使用ISO格式"YYYY-MM-DDThh:mm:ss.sss"在JSON输出上? [英] How to force ISO format "YYYY-MM-DDThh:mm:ss.sss" on the JSON output?
问题描述
我有一个ASP .NET WebApi2 api,它以JSON格式返回一些时间戳.时间戳的分辨率为毫秒.
I have an ASP .NET WebApi2 api which returns some timestamps in JSON format. The timestamps have milliseconds resolution.
通常我会得到这种格式的时间戳,"YYYY-MM-DDThh:mm:ss.sss"
Usually I got timestamps of this format which is fine "YYYY-MM-DDThh:mm:ss.sss"
不幸的是,如果时间戳记以整秒对日期进行编码,则输出格式为"YYYY-MM-DDThh:mm:ss"
(请注意缺少的.sss
)
Unfortunately, if a timestamp happens to encode a date with whole second the output format is "YYYY-MM-DDThh:mm:ss"
(note the missing .sss
")
如何始终在JSON输出上强制使用ISO格式"YYYY-MM-DDThh:mm:ss.sss"
?
How to force ISO format "YYYY-MM-DDThh:mm:ss.sss"
on the JSON output all the time?
推荐答案
将此行添加到WebApiConfig.Register
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// existing stuff
config.Formatters
.JsonFormatter
.SerializerSettings
.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK";
}
}
默认格式为"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"
,最多6 dp.我猜是小写的f
,它似乎可以工作.
The default format is "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"
which gives up to 6 dp. I guessed at lowercase f
and it appears to work.
请注意,K
是时区(对于UTC,则为Z),对于未知日期类型,它也显示空白,这就是为什么您没有任何显示的原因.
Note the K
is timezone (or Z for UTC) it also shows blank for unknown date types which is why you don't have anything showing there.
这篇关于如何强制使用ISO格式"YYYY-MM-DDThh:mm:ss.sss"在JSON输出上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!