Search code examples
c#gitdatetimestring-parsing

How to parse default git date format in C#


How do you parse the default git format to a DateTime in C#? As per What is the format for --date parameter of git commit

The default date format from git looks like Mon Jul 3 17:18:43 2006 +0200.

Right now I don't have control over the output, this strings comes from another tool that printed the date and I need to parse it.


Solution

  • I wouldn't parse this to DateTime, I would parse it to DateTimeOffset since it has a UTC offset value inside of it.

    Why? Because if you parse it to DateTime, you will get a DateTime as Local and it might generate different results for different machines since they can have timezone offsets of that time.

    For example, I'm in Istanbul and we use Eastern European Time which use UTC+02:00. If I run the example of your code with ParseExact method, I will get the 07/03/2006 18:18:43 as a Local time.

    Why? Because in 3 July 2006, my timezone was in a daylight saving time which is UTC+03:00. That's why it generates 1 hour forwarded result. That's the part makes it ambiguous when you parse it to DateTime.

    string s = "Mon Jul 3 17:18:43 2006 +0200";
    DateTimeOffset dto;
    if (DateTimeOffset.TryParseExact(s, "ddd MMM d HH:mm:ss yyyy K", 
                                     CultureInfo.InvariantCulture,
                                     DateTimeStyles.None, out dto))
    {
        Console.WriteLine(dto);
    }
    

    Now, you have a DateTimeOffset as 07/03/2006 17:18:43 +02:00. You can still get the DateTime part with it's .DateTime property but it's Kind will be Unspecified in that case.

    But of course, I suggest to use Noda Time instead which can solve most of the DateTime weirdness.