.netdatetimey2k2-digit-year

Preferred method for handling Y2K date conversions?


Is there a preferred algorithm for converting a 2-digit year into a 4-digit year?

I have a 2-digit birth date (along with month and day) that I want to convert to a C# DateTime. Obiviously, birthdates cannot be in the future, but is there an existing facility in .NET to convert a 2-digit year into a four-digit year?


Solution

  • static int GetFourDigitYear(int year, int maxYear) 
    {
        System.Globalization.GregorianCalendar cal = 
              new System.Globalization.GregorianCalendar();
        cal.TwoDigitYearMax = maxYear;
        return cal.ToFourDigitYear(year);
    }
    

    maxYear should be the current four digit year.


    Edit: OP's solution:

    static int GetFourDigitYear(int year, int pivot) 
    {
        System.Globalization.GregorianCalendar cal = 
              new System.Globalization.GregorianCalendar();
        cal.TwoDigitYearMax = new DateTime.Year + (100-pivot);
        return cal.ToFourDigitYear(year);
    }