Newtonsoft JsonConvert 日期时间格式为 JavascriptSerializer [英] Newtonsoft JsonConvert datetime format as JavascriptSerializer

查看:20
本文介绍了Newtonsoft JsonConvert 日期时间格式为 JavascriptSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 .NET Core 并希望将日期序列化为与 System.Web.Script.JavascriptSerializer 相同的格式,但使用 Newtonsoft jsonconverter(或其他与 .NET Core 兼容的东西,因为 JavascriptSerializer 是 .NET框架).

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).

示例:

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

JsonConvert.Serialize(result1);

JsonConvert.Serialize(result1);

这不会返回我需要的格式:"/日期(1249335477787)/";

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

如何使用 .NET Core 获得这样的约会

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

谢谢

推荐答案

JSON.NET 使用的序列化日期的默认格式ISO 8601,这是正确的大多数解析器和语言(包括 JavaScript)都能理解.过去,使用了您从 JavascriptSerializer 中知道的格式.如果您需要使用该格式,则可以通过 进行配置DateFormatHandling 配置.

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.

在 ASP.NET Core 2.x 中,您可以在 Startup 类的 ConfigureServices 方法中像这样配置它:

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;
});

<小时>

从 ASP.NET Core 3.0 开始,默认使用不同的序列化程序,它没有这个配置选项,但你也可以选择切换回 JSON.NET 并进行相应的配置:


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;
    });

您需要参考 Microsoft.AspNetCore.Mvc.NewtonsoftJson 那么.

这篇关于Newtonsoft JsonConvert 日期时间格式为 JavascriptSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆