简体   繁体   English

使用Datetime.TryParse无法解析我们中的字符串日期

[英]Trouble parsing string date in us with the Datetime.TryParse

I'm trying to put a variable, stored in a string format in a dateTime variable. 我正在尝试将一个以字符串格式存储的变量放入dateTime变量中。

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
System.Globalization.DateTimeFormatInfo usaDateFormatInfo = culture.DateTimeFormat;

string sDataStored = "10/15/2011";
if (DateTime.TryParse(sDataStored , usaDateFormatInfo,       System.Globalization.DateTimeStyles.None, out TestedDateTime))
DateTime dMyUSDateTime = TestedDateTime;

Unfortunately, the final result in my variable is not : "10/15/2011" but "15/10/2011" (the french culture, which is the current culture of the application for the moment). 不幸的是,我变量的最终结果不是:“ 10/15/2011”,而是“ 15/10/2011”(法国文化,这是当前应用程序的当前文化)。

Same result with the TryParseExact. 与TryParseExact的结果相同。

I could go thru a "Convert", inside a "try/catch", but Im sure there are other better way to solve this problem... Thanks for your help. 我可以在“尝试/捕获”中进行“转换”,但是我确定还有其他更好的方法来解决此问题...感谢您的帮助。

When you say the result is 15/11/2011 where are you seeing that? 当您说结果为15/11/2011 ,您在哪里看到? In the debugger? 在调试器中? The debugger will just format the variable according to your current culture (by just calling ToString). 调试器将根据您当前的区域性来格式化变量(只需调用ToString)。

The DateTime object doesn't stored the culture it was parsed from. DateTime对象不存储从中解析出的区域性 You need to pass the culture to it when you convert it back to a string so it formats according to the US culture. 当您将其转换回字符串时,需要将文化传递给它,以便根据美国文化进行格式化。

eg 例如

dMyUsDateTime.ToString(usaDateFormatInfo)

A DateTime doesn't have a culture attached to it. DateTime没有附加的文化。 When you want to display a DateTime value, you need to specify the date/time format to use. 要显示DateTime值时,需要指定要使用的日期/时间格式。 If you don't specify a format (or view the value in the Visual Studio debugger), the current thread's current culture is used. 如果您未指定格式(或在Visual Studio调试器中查看值),则使用当前线程的当前区域性。

string result = someDateTime.ToString("d", new CultureInfo("en-US"));
// result == "10/15/2011"

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

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