8

当文化不是非美国时,我得到一个 String.FormatException 试图转换/解析字符串。奇怪的是,该字符串是通过应用与用于将其解析回字符串的格式和文化完全相同的格式和文化生成的。在下面的代码中,所有这些版本都会失败:

常量字符串文化=“ja-JP”;
常量字符串格式=“dd MMM yyyy”;//原始帖子中的错误包括 {0:}
文化信息信息 = 新文化信息(文化);
Thread.CurrentThread.CurrentCulture = 信息;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(culture);

//string toParse = String.Format(info, format, DateTime.Now); //原帖中的错误
字符串 toParse = DateTime.Now.ToString(format);
System.Diagnostics.Debug.WriteLine(string.Format("文化格式 = {0}, 日期 = {1}",culture, toParse));
尝试
{
    DateTime 输出 = DateTime.ParseExact(toParse, format, CultureInfo.InvariantCulture);
    //日期时间输出 = DateTime.ParseExact(toParse, format, info);
    //日期时间输出 = DateTime.ParseExact(toParse, format, info, DateTimeStyles.None);
    //日期时间输出 = Convert.ToDateTime(toParse, info);
}
捕捉(例外前)
{
    System.Diagnostics.Debug.WriteLine(ex.Message);
}

请注意,en-US 的字符串是“2010 年 2 月 25 日”。ja-JP 的字符串是“25 2 2010”。

知道如何让“25 2 2010”恢复日期吗?

提前致谢。

Edit1:我应该注意,日本文化在这里被硬编码只是作为一个例子。我真的需要它来处理用户设置的任何文化。我需要的是一个解决方案,无论用户的文化如何,日期时间格式都可以工作。我认为单 M 做到了。

编辑 2: M 不适用于英语。有人知道适用于所有文化的格式字符串吗?

4

4 回答 4

3

如果你改变:

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

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

日期已正确解析。

请注意,在您的示例中,您使用一种文化 (ja-JP) 转换为字符串,但使用另一种文化从字符串转换。另一个问题是String.Format接受复合格式字符串 ( "My string to format - {0:dd MMM yyyy}"),但DateTime.ParseExact只需要日期时间格式。

于 2010-02-25T22:19:30.963 回答
0

解析日期时尝试使用单个 M。这就是日本文化的MonthDayPattern示例中使用的内容。

const string format = "{0:dd M yyyy}";
于 2010-02-25T22:14:58.930 回答
0
string text = "25 2 2009";
DateTime date = DateTime.ParseExact(text, "d M yyyy", CultureInfo.InvariantCulture);
于 2010-02-25T22:20:17.597 回答
0

您传递给的格式模式DateTime.ParseExact必须只是日期模式,没有占位符。对于 JP 文化,您只需要使用一个M,因为日期由数字表示,即使MMM在转换为字符串时指定。

        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);
        }
于 2010-02-25T22:24:46.747 回答