Robust DateTime parser library for .NET

Posted by Frank Krueger on Stack Overflow See other posts from Stack Overflow or by Frank Krueger
Published on 2010-03-31T18:19:43Z Indexed on 2010/03/31 18:23 UTC
Read the original article Hit count: 248

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about datetime