简体   繁体   English

DateTime很奇怪

[英]DateTime being weird

How come 怎么会

w.WriteLine(Program.RegisterList[i].DateTime);

Writes : 11/20/2013 01:46:31 PM 11/20/2013 01:46:31 PM11/20/2013 01:46:31 PM

But

w.WriteLine(Convert.ToDateTime(Program.RegisterList[i].DateTime, CultureInfo.InvariantCulture).ToString());

Writes 20/11/2013 1:46:31 PM 20/11/2013 1:46:31 PM

? Isn't invariant culture supposed to make it MM/DD/YY? 不变文化难道不应该成为MM / DD / YY吗? I would like to use the invariant culture method incase a date slips by in DD/MM/YY format. 如果日期以DD / MM / YY格式显示,我想使用不变的文化方法。

Thanks! 谢谢!

Edit: I should mention Program.RegisterList[i].DateTime is a string. 编辑:我应该提到Program.RegisterList[i].DateTime是一个字符串。

Edit2: 编辑2:

MessageBox.Show("11/20/2013 01:46:31 PM");
MessageBox.Show(Convert.ToDateTime("11/20/2013 01:46:31 PM", CultureInfo.InvariantCulture).ToString());
 w.WriteLine(Convert.ToDateTime(Program.RegisterList[i].DateTime, CultureInfo.InvariantCulture).ToString());

You confused yourself by writing code you can't understand anymore. 您通过编写无法理解的代码使自己感到困惑。 A simple rewrite of that one honking statement: 简单地重写那个鸣喇叭的语句:

string s = Program.RegisterList[i].DateTime;
DateTime dt = Convert.ToDateTime(s, CultureInfo.InvariantCulture);
w.WriteLine(dt);

Which should now make it obvious that you are not using InvariantCulture to display the date, it uses the default culture. 现在,这应该很明显表明您没有使用InvariantCulture显示日期,而是使用默认区域性。 Which on your machine puts the day first. 您机器上哪一个最重要。

Always write readable code, it is not slower. 始终编​​写可读代码,这并不慢。

CultureInvariant only guarantees that the format won't change across cultures - it should not be used to display data, only to persist data. CultureInvariant仅保证格式不会随文化而改变-不应用于显示数据,而只能用于保留数据。 If you're concerned about how a string is displayed, you should use a specific culture that displays how you want. 如果您担心字符串的显示方式,则应使用一种特定的区域性来显示所需的方式。 More from MSDN 来自MSDN的更多信息

Having said that, I'm not sure what you mean by a "date slipping by" in a different format. 话虽如此,我不确定您所说的“日期延误”以其他格式表示的意思。 Are you reading a list of dates, and some are in different format? 您是否正在阅读日期列表,其中一些格式不同? If so, I'm afraid CultureInvariant is not the answer. 如果是这样,恐怕CultureInvariant不能解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM