尽管在当前线程中设置了正确的区域设置,但 C# DateTime.ToString() 在 Linux Ubuntu 18.04 上是错误的

标签 c# linux datetime .net-core ubuntu-18.04

好吧,这让我发疯。我已经安装了 ubuntu 18.04 服务器的新实例,它运行我的 dotnetcore 2.2 mvc 应用程序。

尽管区域设置似乎在操作系统和当前线程中正确设置,但 DateTime.ToString() 函数给了我一个奇怪的数据格式:

  • 格式错误:19-05-09 12 12 21 21 02 2
  • 预期格式:19-05-09 12:21:01

在这两种情况下,当前线程本地都是“fr-CA”。 在操作系统中,“locale”命令在这两种情况下都会返回“en_US”。

我检查了 CurrentThread.CurrentCulture.DateTimeFormat 中的 depper,这两种情况似乎并不相同。查看 CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern 变量时:

  • 错误的格式输出模式给了我:HH h mm
  • 良好的格式服务器输出模式给了我:HH:mm

这是什么魔法?我的 Nose 流血了。

最佳答案

在查看了 dotnet 核心中 DateTime 格式的源代码后,我找到了一个修复程序,以确保不带参数的 ToString() 正常工作。

System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.LongTimePattern = "HH:mm:ss";
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";            
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.TimeSeparator = ":";

System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat;

关于尽管在当前线程中设置了正确的区域设置,但 C# DateTime.ToString() 在 Linux Ubuntu 18.04 上是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063807/

相关文章:

linux - 如何在 Linux 中更改文本文件扩展名类型?

linux - 从父文件夹和所有子文件夹中删除特定的命名目录

MySQL - SEC_TO_TIME 给出相同的结果,无论组如何

c# - BeginRead 内存不足异常

c# - 如果给定的 int 是 2 C# 的指数,则返回

linux - 什么是rtnetlink(linux操作系统),netlink和rtnetlink有什么区别?

python - Django 的时区

php - 为什么 DateTime 对象在我执行空操作之前不可用?

c# - 未插入 NULL 值

c# - 带有 WebRequest 的 IP 地址