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?
Use the
DateTime.ParseExact
overload that takes an array of format strings:DateTime's ParseExect Method has some overloads where you can pass multiple format that could be readed if the earlier one is not working. here a sample for you..
Consider using this line:
Notice that I removed one of the spaces between the month and the day. That's because
AllowWhiteSpaces
literally means:You could remove the extra space first and then parse the string: