我正在寻找获取系统日期时间格式的解决方案。
例如:如果我获取 DateTime.Now
?这使用的是哪种日期时间格式?DD/MM/YYYY
等等
如果它在其他地方没有被修改过,那么这将会得到它:
string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
如果使用WinForms应用程序,您还可以查看UICulture
:
string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;
请注意,DateTimeFormat
是一个可读可写的属性,因此它可以被更改。
CultureInfo.CurrentCulture.DateTimeFormat;
不会返回字符串值。如果你想要系统短日期格式,最终调用应该是string sysDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
。 - Joe Almore以上答案并不完全正确。
我曾经遇到这样的情况:我的主线程和UI线程被设计为强制使用“en-US”文化(culture)。 我的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.Threading.Thread threadForCulture = new System.Threading.Thread(delegate(){} );
? - Marwan مروانSystem.DateTime.Now属性返回一个System.DateTime对象。它以二进制格式存储在内存中,大多数情况下,大多数程序员无需考虑此格式。当您显示DateTime值或将其转换为字符串以进行任何其他原因时,它将根据格式字符串进行转换,该字符串可以指定任何您喜欢的格式。
就这个意义而言,回答您的问题“如果我获取DateTime.Now,那么使用哪种日期时间格式?”是“它根本不使用任何DateTime格式,因为您还没有格式化它”。
通过调用ToString的重载来指定格式,或者(可选)如果您使用System.String.Format。也有一个默认格式,因此您不必总是指定格式。如果您想知道如何确定默认格式,则应查看Oded的答案。
DateTime.ToString()
或 DateTimeOffset.ToString()
。这将按照当前区域设置格式化 DateTime。它基本上结合了当前区域设置的 DateTimeFormat 中的 ShortDate 和 LongTime。dd-MM-yyyy
格式表示短日期,HH:mm:ss
格式表示长时间,那么以下代码将打印24-02-2023 18:15:22
。var dateTimeObject = DateTime.UtcNow;
var formattedString = dateTimeObject.ToString();
Console.WriteLine("Date and Time: " + formattedString);
24-02-2023 18:23:22 +05:30
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern