如何获取系统日期时间格式

本文关键字:系统 日期 时间 格式 获取 何获取 | 更新日期: 2023-09-27 17:58:12

我正在寻找一种获取系统日期-时间格式的解决方案。

例如:如果我得到DateTime.Now?这使用的是哪种日期时间格式?DD/MM/YYYY

如何获取系统日期时间格式

如果它在其他地方没有更改,这将得到它:

string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;

如果使用WinForms应用程序,您还可以查看UICulture:

string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;

请注意,DateTimeFormat是一个读写属性,因此它可以更改。

以上答案并不完全正确。

我有一种情况,我的主线程和UI线程被迫处于"en-US"文化中(按设计)。我的Windows DateTime格式为"dd/MM/yyyy"

string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;

返回"MM/dd/yyyy",但我想获得真正的Windows格式。我能够做到这一点的唯一方法是创建一个伪线程。

System.Threading.Thread threadForCulture = new System.Threading.Thread(delegate(){} );
string format = threadForCulture.CurrentCulture.DateTimeFormat.ShortDatePattern;

System.DateTime.Now属性返回一个System.DateTime。它以二进制格式存储在内存中,大多数程序员在大多数情况下都不需要考虑它。当您显示DateTime值或出于任何其他原因将其转换为字符串时,它将根据格式字符串进行转换,该字符串可以指定您喜欢的任何格式。

从最后一个意义上讲,你的问题"如果我得到DateTime。现在,它使用的是哪种日期时间格式?"的答案是"它根本没有使用任何DateTime格式,因为你还没有格式化它"。

您可以通过调用ToString的重载来指定格式,或者(可选)如果您使用System.String.format。还有一个默认格式,所以您不必总是指定格式。如果你问如何确定默认格式,那么你应该看看奥德的答案。

如果希望在格式化字符串中同时包含日期和时间,可以简单地使用DateTime.ToString()DateTimeOffset.ToString()。这将按照CurrentCulture设置DateTime的格式。它基本上结合了CurrentCulture的DateTimeFormat中的ShortDate和LongTime。

请查看文档。

示例:

如果您的系统对ShortDate使用dd-MM-yyyy格式,对LongTime使用HH:mm:ss格式,则以下代码将打印24-02-2023 18:15:22

var dateTimeObject = DateTime.UtcNow;
var formattedString = dateTimeObject.ToString();
Console.WriteLine("Date and Time: " + formattedString);

注:如果您使用的是DateTimeOffset,它还会将偏移量添加到格式化的字符串中。例如:24-02-2023 18:23:22 +05:30

使用以下内容:

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern