Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Parse always throws exception in a specific culture

Tags:

c#

.net

I have some old log files I have to parse - apparently the date time was saved like: 18/12/2012 11:09:39 p.m. - All my attempts to parse these have failed. I am completely lost on this - Any help or direction would be great!

 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 ;

            }
        }
like image 390
BillyDvd Avatar asked Apr 19 '13 20:04

BillyDvd


People also ask

What is DateTime parse exception?

Class DateTimeParseExceptionAn exception thrown when an error occurs during parsing. This exception includes the text being parsed and the error index. Implementation Requirements: This class is intended for use in a single thread. Since: 1.8 See Also: Serialized Form.

What does DateTime parse do?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

How to use DateTime Parse in c#?

The DateTime. ParseExact method converts the specified string representation of a datetime to a DateTime . The datetime string format must match the specified format exactly; otherwise an exception is thrown. Date & time is culture specific; the methods either use the current culture or accept a specific culture.


1 Answers

Some dates are correct in the log file(s) some have the odd formatting that end in p. m. or p.m.. All methods above seem to fail - and yes I tried them all :( This was my hack/fix for the problem:

     CultureInfo cultureInfo = new CultureInfo( "es-MX" , true );
     Date = DateTime.Parse( date.Replace( "p. m." , "PM" ).Replace( "p.m." , "PM" ).Replace( "." , "" ).ToUpper() , cultureInfo );
like image 121
BillyDvd Avatar answered Oct 06 '22 00:10

BillyDvd