views:

194

answers:

3

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?

+1  A: 
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);
}
Mehrdad Afshari
A static function similar to this one ended up being my solution, except that i pass a pivot, rather than a year. For birth dates, the pivot is 100 years ago.
Ian Boyd
+1  A: 

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.

Chris Lively
As a side note, this link ( http://www.theiet.org/factfiles/it/dates.cfm?type=pdf ) has a list of potential dates from 2001 to 2100 that could cause problems for various systems.
Chris Lively
A: 

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.

San Jacinto