String.FormatException with DateTime in non US Culture

大憨熊 提交于 2019-12-05 03:03:35

If you change:

DateTime output = DateTime.ParseExact(
    toParse, format, CultureInfo.InvariantCulture);

to

DateTime output = DateTime.ParseExact(toParse, "dd MMM yyyy", info);

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}"), but DateTime.ParseExact is expecting only the date time format.

Try using a single M when parsing the date. That is what is used in the example for the MonthDayPattern for Japanese culture.

const string format = "{0:dd M yyyy}";
string text = "25 2 2009";
DateTime date = DateTime.ParseExact(text, "d M yyyy", CultureInfo.InvariantCulture);

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 one M since the dates are represented by numbers even when MMM is specified when converting to a string.

        const string culture = "ja-JP";
        const string FROM_STRING_FORMAT = "dd M yyyy";
        const string TO_STRING_FORMAT = "{0:" + FROM_STRING_FORMAT + "}";
        CultureInfo info = new CultureInfo(culture);
        Thread.CurrentThread.CurrentCulture = info;
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(culture);

        string toParse = String.Format(info, TO_STRING_FORMAT, DateTime.Now);
        Console.WriteLine(string.Format("Culture format = {0}, Date = {1}", culture, toParse));
        try
        {
            DateTime output = DateTime.ParseExact(toParse, FROM_STRING_FORMAT, CultureInfo.InvariantCulture);
            Console.WriteLine(output);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!