Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robust DateTime parser library for .NET

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:

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.

like image 409
Frank Krueger Avatar asked Mar 31 '10 18:03

Frank Krueger


1 Answers

In addition to TryParse on DateTime, .Net also provides the DateTimeOffset struct which offers access to the UTC offset as another property on the struct, allowing you to store time zone info and datetime info together.

  • MSDN article
like image 98
Joel Avatar answered Sep 17 '22 23:09

Joel