Robust DateTime parser library for .NET
- by Frank Krueger
Hello, I am writing an RSS and Mail reader app in C# (technically MonoTouch).
I have run into the issue of parsing DateTimes. I see a lot of variance in how dates are presented in the wild and have begun writing a function like this:
public static DateTime ParseTime(string timeStr) {
var formats = new string[] {
"ddd, d MMM yyyy H:mm:ss \"GMT+00:00\"",
"d MMM yyyy H:mm:ss \"EST\"",
"yyyy-MM-dd\"T\"HH:mm:ss\"Z\"",
"ddd MMM d HH:mm:ss \"+0000\" yyyy",
};
try {
return DateTime.Parse(timeStr);
}
catch (Exception) {
}
foreach (var f in formats) {
try {
var t = DateTime.ParseExact(timeStr, f,
CultureInfo.InvariantCulture);
return t;
}
catch (Exception) {
}
}
return DateTime.MinValue;
}
This, well, makes me sick. Three points. (1) It's silly of me to think that I can actually collect a format list that will cover everything out there. (2) It's wrong! Notice that I'm treating an EST date time as UTC (since .NET seems oblivious to time zones). (3) I don't like using exceptions for logic.
I am looking for an existing library (source only please) that is known to handle a bunch of these formats.
Also, I would like to keep using UTC DateTimes throughout my code so whatever library is suggested should be able to produce DateTimes.
Is there anything out there like this?