views:

61

answers:

3

I have a textbox where users can enter a year "YY" and I am parsing it using:

int year;
if (int.TryParse(txtYear.Text, out year))
{
    args.Year = year;
}

The problem is TryParse will convert '07' into '7' and my method is expecting the year to be in the format YYYY (e.g. input "07" should be "2007"). What is the best way to do this conversion?

+4  A: 

The best way is to request the user to enter all four digits. Part of the reason for the 2K problem was legacy systems that assumed 2 digits would always be enough.

If you have to do this, then just add 2000 to your result.

int year;
if (int.TryParse(txtYear.Text, out year))
{
    args.Year = year + 2000;
}

You might want to add 1900 instead of 2000 for for sufficiently large inputs ("99" -> 1999, "00" -> 2000) depending on how likely it is that your users intended 2099 when they entered "99".

Mark Byers
+5  A: 
DateTime date;
if (DateTime.TryParseExact("07", "yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    Console.WriteLine(date.Year);
}

As @Mark suggested though pay attention to the 2K problem.

I would simply ask the users to enter the year into YYYY format.

Darin Dimitrov
I did some testing of this method and it currently returns dates in the range 1930 - 2029. I wonder if they will change that before it gets to 2030...
Mark Byers
A: 
int year;
if (int.TryParse(txtYear.Text, out year))
{
    args.Year = DateTime.Now.Year - (DateTime.Now.Year%100) + year;
}
jgauffin