我正在寻找获取系统日期时间格式的解决方案。
例如:如果我得到
DateTime.Now
?这是使用哪种日期时间格式? DD/MM/YYYY
等
如果其他地方没改过,这个就搞定了:
string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
如果使用 WinForms 应用程序,您还可以查看
UICulture
:
string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;
DateTimeFormat
是读写属性,所以可以改变
以上答案不完全正确
我有一种情况,我的主线程和我的 UI 线程被迫处于“en-US”文化(设计)。 我的 Windows 日期时间格式是“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.Now,这是使用哪种日期时间格式?”是“它根本没有使用任何 DateTime 格式,因为你还没有格式化它”。
您可以通过调用 ToString 的重载来指定格式,或者(可选)如果您使用 System.String.Format。还有一种默认格式,因此您不必总是指定格式。如果您询问如何确定默认格式,那么您应该查看 Oded 的回答。
如果你想要格式化字符串中的日期和时间,你可以简单地使用
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