DateTime.Parse始终在特定区域性中引发异常

时间:2013-04-19 20:46:43

标签: c# .net

我有一些旧的日志文件我必须解析 - 显然日期时间保存如下: 18/12/2012 11:09:39下午 - 我所有解析这些的尝试都失败了。 我完全迷失了 - 任何帮助或方向都会很棒!

 CultureInfo cultureInfo = new CultureInfo( "es-MX" , true );
        string date = "18/12/2012 11:09:39 p.m.";

        DateTime dt = new DateTime( 2012 , 12 , 18 , 11 , 9 , 39 ).AddHours( 12 );

        this.richTextBox1.Text += date + Environment.NewLine;
        this.richTextBox1.Text += dt.ToString( cultureInfo ) + Environment.NewLine;
        this.richTextBox1.Text += dt.ToString() + Environment.NewLine;

        foreach ( var item in richTextBox1.Lines )
        {
            try
            {
               DateTime d=  DateTime.Parse( item );
               this.richTextBox1.Text += d.ToString() + Environment.NewLine ;

            }
            catch ( Exception ee)
            {
                this.richTextBox1.Text += ee.Message + Environment.NewLine ;

            }
        }

4 个答案:

答案 0 :(得分:3)

某些日期在日志文件中是正确的,有些日期格式以p结尾。米或者p.m .. 以上所有方法似乎都失败了 - 是的,我尝试了所有方法:( 这是我解决问题的方法:

     CultureInfo cultureInfo = new CultureInfo( "es-MX" , true );
     Date = DateTime.Parse( date.Replace( "p. m." , "PM" ).Replace( "p.m." , "PM" ).Replace( "." , "" ).ToUpper() , cultureInfo );

答案 1 :(得分:2)

尝试使用DateTime.TryParseExact()。这是我在LINQPad中运行的一个例子。

void Main()
{
    System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo( "es-MX" , true );
    string date = "18/12/2012 11:09:39 p.m.";

    DateTime dt = new DateTime( 2012 , 12 , 18 , 11 , 9 , 39 ).AddHours( 12 );

    DateTime d;
    string[] styles = {"dd/MM/yyyy hh:mm:ss tt"}; // This doesn't have to be an array - could be string
    DateTime.TryParseExact(date, styles, cultureInfo, System.Globalization.DateTimeStyles.None, out d);

    d.Dump();
}

答案 2 :(得分:0)

尝试使用cultureInfo变量作为Parse的第二个参数。这将使用culture作为格式提供者。

DateTime d =  DateTime.Parse( item, cultureInfo );

答案 3 :(得分:0)

问题是你没有指定在调用Parse()时使用的文化。您的调用使用当前线程的CurrentCulture属性:

DateTime d=  DateTime.Parse( item );

你需要的神奇咒语是:

DateTime instance = DateTime.Parse( text , CultureInfo.GetCultureInfo("es-MX") ) ;

您的另一种选择是改变当前线程的文化:

CultureInfo mexico = CultureInfo.GetCultureInfo( "es-MX" );
Thread.CurrentThread.CurrentCulture = mexico;
在致电DateTime.Parse()之前

。在启动时这样做你应该很高兴(只要使用墨西哥语西班牙语有助于你的目的。请注意,改变当前的文化不会改变事物的显示方式:这是线程的CurrentUICulture属性的责任。 / p>

相关问题