开发者

Trouble parsing string date in us with the Datetime.TryParse

开发者 https://www.devze.com 2023-04-09 07:59 出处:网络
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\");

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/1开发者_开发百科0/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.


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.

dMyUsDateTime.ToString(usaDateFormatInfo)


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.

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

精彩评论

暂无评论...
验证码 换一张
取 消