简体   繁体   English

使用Dot Net Core 2 WebApi中的Json序列化将C#DateTime自动转换为JavaScript日期

[英]Convert C# DateTime to JavaScript date automatically using Json Serialization in Dot Net Core 2 WebApi

Is it possible to convert C# DateTime fields to JavaScript dates automatically when returning results from a Dot Net Core 2.0 WebApi Controller call? 从Dot Net Core 2.0 WebApi Controller调用返回结果时,是否可以自动将C#DateTime字段转换为JavaScript日期?

At the moment, when a DateTime value is returned from a server side call, it returns in the format: "2013-02-01T00:00:00" 目前,从服务器端调用返回DateTime值时,其返回格式为:“ 2013-02-01T00:00:00”

I would have thought that it would be possible to set the JsonSerializer options to return the value already converted into a JavaScript date without needing to parse it via a secondary parser such as moment. 我本以为可以设置JsonSerializer选项以返回已经转换为JavaScript日期的值,而无需通过诸如时刻的辅助解析器对其进行解析。

Anyone know how to do this? 有人知道怎么做吗?

you should add this following line to your startup.cs class in ConfigureService function: 您应该将此行添加到ConfigureService函数中的startup.cs类中:

services
            .AddMvc()
            .AddJsonOptions(x => x.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat);

Then you can get date in json format while serialize data. 然后您可以在序列化数据时以json格式获取日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM