Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime parsing

I am writing a syslog server that receives syslog messages and stores them in a database.

I am trying to parse the date string received in the message into a DateTime structure.

For the following examples, I'll be using an underscore in place of whitespace for clarity; the actual strings received have spaces.

The string I received is in the format "Jun__7_08:09:10" - please note the two whitespaces between the month and day.

If the day is after the 10th, the strings become "Jun_10_08:09:10" (one whitespace).

If I parse with:

DateTime.ParseExact(Log.Date, "MMM  d HH:mm:ss", CultureInfo.InvariantCulture);

it works for strings from the 1st to 9th but throws exception from the 10th forward, and if I parse with one space, it throws an exception on the 1st to 9th (and works from the 10th on).

What is the correct way to parse this string?

like image 834
Akobold Avatar asked Jun 07 '13 13:06

Akobold


People also ask

What is DateTime ParseExact in C#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

What is date parse in SQL?

The date function used to parse a date or datetime value, according to a given format string. A wide variety of parsing options are available.


2 Answers

Consider using this line:

DateTime.ParseExact(Log.Date,
    "MMM d HH:mm:ss",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AllowWhiteSpaces);

Notice that I removed one of the spaces between the month and the day. That's because AllowWhiteSpaces literally means:

Specifies that s may contain leading, inner, and trailing white spaces not defined by format.

like image 134
Mike Perrenoud Avatar answered Oct 08 '22 03:10

Mike Perrenoud


Use the DateTime.ParseExact overload that takes an array of format strings:

DateTime.ParseExact(Log.Date, 
                    new [] {"MMM  d HH:mm:ss", "MMM d HH:mm:ss"}, 
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None);
like image 22
Oded Avatar answered Oct 08 '22 03:10

Oded