Newtonsoft JsonConvert datetime format as JavascriptSerializer

爷,独闯天下 提交于 2021-02-11 12:28:44

问题


I'm using .NET Core and want to serialize a date into the same format as the System.Web.Script.JavascriptSerializer, but using Newtonsoft jsonconverter instead (or something else compatible with .NET Core since the JavascriptSerializer is .NET framework).

Example:

DateTime result1;
var dt1 = DateTime.TryParse("12.06.2012 10:34:00",CultureInfo.GetCultureInfo("DA-dk"), DateTimeStyles.None, out result1);

JsonConvert.Serialize(result1);

This does NOT return a format like this that I need: "/Date(1249335477787)/";

How can I get a date like this with .NET Core

Thanks


回答1:


The default format for serializing dates that JSON.NET uses is ISO 8601 which is properly understood by the majority of parsers and languages (including JavaScript). In the past, the format that you know from the JavascriptSerializer has been used. If you need to use that format, then you can configure it through the DateFormatHandling configuration.

In ASP.NET Core 2.x, you can configure it like this within the ConfigureServices method in your Startup class:

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
});

Starting with ASP.NET Core 3.0, a different serializer is used by default which will not have this configuration option, but you can choose to switch back to JSON.NET there too and configure it accordingly:

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
    });

You will need a reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson then though.



来源:https://stackoverflow.com/questions/56539179/newtonsoft-jsonconvert-datetime-format-as-javascriptserializer

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