I am getting a String.FormatException trying to convert/parse a string when the culture is other than non-US. The odd thing is that the string was generated by applying the very same format and culture as those being used to parse it back into a string. In the code below, all of these versions will fail:
const string culture = "ja-JP"; const string format = "dd MMM yyyy"; //error in orignal post included {0:} CultureInfo info = new CultureInfo(culture); Thread.CurrentThread.CurrentCulture = info; Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(culture); //string toParse = String.Format(info, format, DateTime.Now); //error in original post string toParse = DateTime.Now.ToString(format); System.Diagnostics.Debug.WriteLine(string.Format("Culture format = {0}, Date = {1}", culture, toParse)); try { DateTime output = DateTime.ParseExact(toParse, format, CultureInfo.InvariantCulture); //DateTime output = DateTime.ParseExact(toParse, format, info); //DateTime output = DateTime.ParseExact(toParse, format, info, DateTimeStyles.None); //DateTime output = Convert.ToDateTime(toParse, info); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); }
Note that the string for en-US is "25 Feb 2010". The string for ja-JP is "25 2 2010".
Any idea how to get "25 2 2010" back into a date?
Thanks in advance.
Edit1: I should note that the Japanese culture is hard-coded here only as an example. I really need this to work with whatever culture is set by the user. What I need is a solution where the date time format works no matter what the user's culture. I think the single M does it.
Edit 2: M doesn't work for English. Anyone know a format string that works for all cultures?
The format pattern you pass to
DateTime.ParseExact
has to be just the date pattern, without the placeholder. And for JP culture, you need to use just oneM
since the dates are represented by numbers even whenMMM
is specified when converting to a string.Try using a single M when parsing the date. That is what is used in the example for the MonthDayPattern for Japanese culture.
If you change:
to
the date is correctly parsed.
Note that in your example you are using a culture (ja-JP) to convert to string but another culture to convert from string. Another problem is that
String.Format
accepts a composite format string ("My string to format - {0:dd MMM yyyy}"
), butDateTime.ParseExact
is expecting only the date time format.