使用 Datetime.TryParse 解析我们的字符串日期时遇到问题
我试图将以字符串格式存储的变量放入日期时间变量中。
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;
不幸的是,我的变量的最终结果不是:“10/15/2011”而是“15/10/2011”(法国文化,这是目前应用程序的当前文化)。
与 TryParseExact 的结果相同。
我可以在“try/catch”中通过“Convert”,但我确信还有其他更好的方法来解决这个问题...... 感谢您的帮助。
I'm trying to put a variable, stored in a string format in a dateTime variable.
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).
Same result with the 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您说结果是
15/11/2011
时,您在哪里看到的?在调试器中?调试器将根据您当前的区域性格式化变量(通过调用 ToString)。DateTime 对象不存储解析它的区域性。当您将其转换回字符串时,您需要将区域性传递给它,以便它根据美国区域性进行格式化。
例如
When you say the result is
15/11/2011
where are you seeing that? In the debugger? The debugger will just format the variable according to your current culture (by just calling ToString).The DateTime object doesn't stored the culture it was parsed from. You need to pass the culture to it when you convert it back to a string so it formats according to the US culture.
e.g.
DateTime 没有附加文化。当您想要显示日期时间值时,您需要指定要使用的日期/时间格式。如果未指定格式(或在 Visual Studio 调试器中查看值),则使用当前线程的当前区域性。
A DateTime doesn't have a culture attached to it. When you want to display a DateTime value, you need to specify the date/time format to use. If you don't specify a format (or view the value in the Visual Studio debugger), the current thread's current culture is used.