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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With