Search code examples
c#windows-10windows-server-2012-r2datetime-parsing

DateTime.ParseExact - different outputs on Windows 10 and WinServer2012R2


I found out that this line:

DateTime.ParseExact("Jan 30", "MMM yy", null, System.Globalization.DateTimeStyles.None)

creates the date:

2030-01-01

...on my Windows 10 machine, but on Windows Server 2012 R2 the output is:

1930-01-01

Does anybody know how to get Windows Server 2012 to parse the date as 2000 instead of 1900?


Solution

  • It's based on the culture's default calendar's TwoDigitYearMax property. If you change that property value, you'll get a different result:

    using System;
    using System.Globalization;
    
    class Program
    {
        static void Main(string[] args)
        {
            var culture = CultureInfo.CurrentCulture;
            
            // Clone returns a *mutable* copy.
            culture = (CultureInfo) culture.Clone();
            
            culture.DateTimeFormat.Calendar.TwoDigitYearMax = 2029;
            var result = DateTime.ParseExact("Jan 30", "MMM yy", culture, System.Globalization.DateTimeStyles.None);
            Console.WriteLine(result.Year); // 1930
    
            culture.DateTimeFormat.Calendar.TwoDigitYearMax = 2129;
            result = DateTime.ParseExact("Jan 30", "MMM yy", culture, System.Globalization.DateTimeStyles.None);
            Console.WriteLine(result.Year); // 2030
        }
    }