Scott Chamberlain Scott Chamberlain - 9 months ago 62
C# Question

Convert a two digit year to a four digit year

This is a question of best practices. I have a utility that takes in a two digit year as a string and I need to convert it to a four digit year as a string. right now I do

//DOB's format is "MMM (D)D YY" that first digit of the day is not there for numbers 1-9
string tmpYear = rowIn.DOB.Substring(rowIn.DOB.Length - 3, 2); //-3 because it is 0 indexed
if (Convert.ToInt16(tmpYear) > 50)
tmpYear = String.Format("19{0}", tmpYear);
tmpYear = String.Format("20{0}", tmpYear);

I am sure I am doing it horribly wrong, any pointers?

Answer Source

The .NET framework has a method that does exactly what you want:

int fourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(twoDigitYear)

That way you will correctly adhere to current regional settings as defined in Control Panel (or group policy):

Regional settings