启用邪恶-覆盖System.DateTime的默认ToString

Had an interesting back and forth with Tom Wayson today. He wanted to be able to "modify the default behavior of DateTime.ToString()."

今天与汤姆·韦森(Tom Wayson)来回有趣。 他希望能够“修改DateTime.ToString()的默认行为”。

So, pushing aside issues of localization and the questions of "why would you want to do that?" let's look at the problem.

因此,撇开本地化问题和“您为什么要这样做?”的问题,放在一边让我们看一下问题。

He has an intranet application and doesn't need to localize it. He wants to 'enforce' a specific date/time format and wants to avoid writing DateTime.Now.ToString("MM/dd/yy HH:mm:ss") everytime. He also doesn't want to explicitly set the system-wide settings in Control Panel | Regional Settings.

他有一个Intranet应用程序,不需要对其进行本地化。 他想“强制执行”特定的日期/时间格式,并希望避免每次都写DateTime.Now.ToString(“ MM / dd / yy HH:mm:ss”)。 他也不想在“控制面板” |“控制面板”中显式设置系统范围的设置。 区域设置。

He noted that the output of DateTime.Now.ToString on a standard en-us machine in the states gave this output:

他指出,在标准的en-us计算机上,各州的DateTime.Now.ToString的输出给出了以下输出:

8/15/2006 3:27:27 PM

2006/8/15下午3:27:27

It looks like the output of ToString is the combination of the DateTimeFormatInfo.ShortDatePattern and DateTimeFormatInfo.ShortTimePattern. So, he: 

看起来ToString的输出是DateTimeFormatInfo.ShortDatePattern和DateTimeFormatInfo.ShortTimePattern的组合。 因此,他:

Imports System

进口制度

Imports System.Globalization

导入系统全球化

Public Module MyModule

公共模块MyModule

    Sub Main()

子Main()

        Dim customCulture As CultureInfo = New CultureInfo("en-US")

Dim customCulture as CultureInfo = New CultureInfo( “ en-US” )

        customCulture.DateTimeFormat.ShortDatePattern = "MM/dd/yy"

customCulture.DateTimeFormat.ShortDatePattern = “ MM / dd / yy”

        'HH means 24 hour time, while hh means 12 hour time        customCulture.DateTimeFormat.ShortTimePattern = "HH:mm:ss"

'HH表示24小时制,而hh表示12小时制customCulture.DateTimeFormat.ShortTimePattern = “ HH:mm:ss”

        System.Threading.Thread.CurrentThread.CurrentCulture = customCulture

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture

        System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture

System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture

        WL(DateTime.Now.ToString())

WL(DateTime.Now.ToString())

        WL(DateTime.Now.ToShortDateString())

WL(DateTime.Now.ToShortDateString())

        WL(DateTime.Now.ToShortTimeString())

WL(DateTime.Now.ToShortTimeString())

    End Sub

结束子

    Sub WL(ByVal text As Object)

Sub WL( ByVal text as Object )

        Console.WriteLine(text)

Console.WriteLine(文本)

    End Sub

结束子

End Module 

终端模块

But the output was still 12 hour time:

但是输出仍然是12小时:

8/15/06 3:28:34 PM

2006/8/15下午3:28:34

Ah...a little Reflectoring shows us that the default format string for System.DateTime is "G" as in System.DateTime.ToString("G") where G is one of the presets.

啊...稍微的Reflectoring向我们展示了System.DateTime的默认格式字符串是“ G”,就像System.DateTime.ToString(“ G”)一样,其中G是预设之一。

From PowerShell we see:

在PowerShell中,我们看到:

PS>C:\Documents and Settings\shanselm\Desktop[DateTime]::Now.ToString("g")
8/15/2006 3:28 PMPS>C:\Documents and Settings\shanselm\Desktop[DateTime]::Now.ToString("G")
8/15/2006 3:28:02 PMPS>C:\Documents and Settings\shanselm\Desktop[DateTime]::Now.ToString()
8/15/2006 3:28:15 PM

PS> C:\ Documents and Settings \ shanselm \ Desktop [DateTime] ::: Now.ToString(“ g”) 2006/8/15下午3:28 PS> C:\ Documents and Settings \ shanselm \ Desktop [DateTime] ::: Now.ToString(“ G”) 2006/8/15下午3:28:02 PS> C:\ Documents and Settings \ shanselm \ Desktop [DateTime] :: Now.ToString() 2006/8/15下午3:28:15

So we add:

因此,我们添加:

Imports System

进口制度

Imports System.Globalization

导入系统全球化

Public Module MyModule

公共模块MyModule

    Sub Main()

子Main()

        Dim customCulture As CultureInfo = New CultureInfo("en-US")

Dim customCulture as CultureInfo = New CultureInfo( “ en-US” )

        customCulture.DateTimeFormat.ShortDatePattern = "MM/dd/yy"

customCulture.DateTimeFormat.ShortDatePattern = “ MM / dd / yy”

        'HH means 24 hour time, while hh means 12 hour time        customCulture.DateTimeFormat.ShortTimePattern = "HH:mm:ss"               customCulture.DateTimeFormat.LongTimePattern = "HH:mm:ss"

'HH表示24小时制,而hh表示12小时制customCulture.DateTimeFormat.ShortTimePattern = “ HH:mm:ss” customCulture.DateTimeFormat.LongTimePattern = “ HH:mm:ss”

        System.Threading.Thread.CurrentThread.CurrentCulture = customCulture

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture

        System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture

System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture

        WL(DateTime.Now.ToString())

WL(DateTime.Now.ToString())

        WL(DateTime.Now.ToShortDateString())

WL(DateTime.Now.ToShortDateString())

        WL(DateTime.Now.ToShortTimeString())

WL(DateTime.Now.ToShortTimeString())

    End Sub

结束子

    Sub WL(ByVal text As Object)

Sub WL( ByVal text as Object )

        Console.WriteLine(text)

Console.WriteLine(文本)

    End Sub

结束子

End Module 

终端模块

And gets the output he expects, indicating that "G" is the combination of a ShortDate and a LongTime.

并获得他期望的输出,表明“ G”是ShortDate和LongTime的组合。

8/15/2006 15:28:57

8/15/2006 15:28:57

翻译自: https://www.hanselman.com/blog/enabling-evil-overriding-systemdatetimes-default-tostring

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 .NET 6 Web API 的 `Program.cs` 文件中,你可以通过配置全局的 JSON 序列化设置来统一设置日期时间的返回类型为 "YYYY-MM-DD"。以下是示例代码: ```csharp using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using System.Text.Json; public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureAppConfiguration((hostingContext, config) => { // 配置全局的 JSON 序列化设置 config.Services.Configure<JsonOptions>(options => { options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.SerializerOptions.PropertyNameCaseInsensitive = true; options.SerializerOptions.WriteIndented = true; options.SerializerOptions.Converters.Add(new DateTimeConverter()); }); }); webBuilder.UseStartup<Startup>(); }); } // 自定义日期时间格式转换器 public class DateTimeConverter : JsonConverter<DateTime> { private const string DateFormat = "yyyy-MM-dd"; public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return DateTime.ParseExact(reader.GetString(), DateFormat, CultureInfo.InvariantCulture); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString(DateFormat)); } } ``` 在上述代码中,我们通过 `ConfigureAppConfiguration` 方法配置了全局的 JSON 序列化设置,使用了自定义的日期时间格式转换器 `DateTimeConverter`,将日期时间格式转换为 "YYYY-MM-DD" 的字符串形式。 确保你的项目引用了 `Microsoft.AspNetCore.Mvc.NewtonsoftJson` 包,并在 `Startup.cs` 文件中使用以下代码启用 Newtonsoft.Json 替代系统默认的 System.Text.Json: ```csharp services.AddControllers().AddNewtonsoftJson(); ``` 这样,你的 .NET 6 Web API 就会在返回 JSON 数据时统一使用 "YYYY-MM-DD" 的日期格式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值