如何获取System DateTime格式?

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

例如:如果我得到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.Now,哪个日期时间格式使用?” 是“它根本没有使用任何DateTime格式,因为你还没有格式化它”。

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