2011-06-01 96 views
25

我正在寻找一个解决方案来获取系统日期时间格式。如何获取系统日期时间格式?

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

+0

你想获得特定格式的日期时间?那么我们需要知道你想要帮助你的格式。 – 2011-06-01 07:57:14

+0

要明确,DateTime.Now不是任何格式。它纯粹是一个二进制数。 – pm100 2017-10-18 21:48:21

回答

41

如果它没有被其他地方的改变,这会得到它:

string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern; 

如果使用WinForms应用程序,你也可以看看的UICulture:

string sysUIFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern; 

注意DateTimeFormat是一个读写属性,所以可以被更改。

+3

调用'CultureInfo.CurrentCulture.DateTimeFormat;'不返回字符串值。最后的调用应该是'string sysDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;'以防你正在寻找系统短日期格式。 – 2014-01-15 19:45:26

+0

@JoeAlmore - 感谢您的评论。答案已更新。 – Oded 2014-01-15 19:50:23

1

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

在这最后的意义上,你的问题的答案是“如果我得到DateTime.Now,哪个日期时间格式是使用?”是“它根本没有使用任何DateTime格式,因为你还没有格式化它”。

可以通过调用ToString的重载来指定格式,或者如果使用System.String.Format,则可以(可选)指定格式。还有一个默认格式,所以你不一定要指定格式。如果你在问如何确定默认格式,那么你应该看看Oded的答案。

11

上面的答案并不完全正确。

我有一个情况,我的主线程和我的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; 
相关问题