Question

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?

Was it helpful?

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);
}

OTHER TIPS

Various systems use different breakpoint dates depending on their underlying data requirements.

In your case, it is most likely safe to assume that the years 00 through 09 are 2000+ whereas any other values (10 through 99) are 1900+

The question you have to ask yourself is:what is the likelihood of having 100+ year old people as records currently in your system.

You should do this calculation exactly once, store it, and have all of your code going forward using 4 digit years.

it would occur to me that if a person was potentiall born january 3, 2007 that the likelihood that they were born on the same day of the week 100 years earlier is slightly less than 1/7. If this probability is too high for your liking, then I doubt that there is a good way to automate this unless you also store their age.

edit: of course, there is a formula (knowing algorithmically how the calendar works) that will lower this probability... but in the end, you're still likely to have some errant results if you don't store their age.

edit 2: of course, if you have their age, then you don't need a calendar algorithm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top