Hello, I am writing an RSS and Mail reader app in C# (technically MonoTouch).
I have run into the issue of parsing DateTime
s. I see a lot of variance in how dates are presented in the wild and have begun writing a function like this:
static string[] DateTimeFormats = 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",
};
public static DateTime ParseTime(string timeStr) {
var r = DateTime.MinValue;
var styles = DateTimeStyles.AdjustToUniversal |
DateTimeStyles.AllowWhiteSpaces;
if (DateTime.TryParse(timeStr,
CultureInfo.InvariantCulture,
styles,
out r)) {
return r;
}
else {
if (DateTime.TryParseExact(timeStr,
DateTimeFormats,
CultureInfo.InvariantCulture,
styles,
out r)) {
return r; // BUGGY! Ignores time zone!!
}
}
Console.WriteLine ("BAAAAAAAAAAAAD");
return DateTime.MinValue;
}
This, well, makes me sick. Two 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).
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?
Update It would seem I was unclear in my request. I am looking for a library that knows a lot of these wild format strings. DateTime.Parse/DateTime.TryParse only know a couple formats, and they certainly don't understand timezones (you can see I am already using it). I need something more powerful than DateTime.Parse/DateTime.TryParse.
Update 2 Everyone was dwelling on the fact that I was using Parse instead of TryParse. I have switched the code. But it's still wrong and incomplete.