How to convert 2-digit year to 4-digit year in C#

Cesar Aguirre - Mar 17 '21 - - Dev Community

Today I was working with credit cards and I needed to convert a 2-digit year to a 4-digit one in C#. The first thing that came to my mind was adding 2000 to it. But it didn't feel right. It wouldn't be a problem in hundreds of years.

To convert 2-digit year into a 4-digit year, you can use the ToFourDigitYear method inside the Calendar class of your current culture.

CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(21)
// 2021
Enter fullscreen mode Exit fullscreen mode

But, if you're working with a string containing a date, you can create a custom CultureInfo instance and set the maximum year to 2099. After that, you can parse the string holding the date with the custom culture. Et voilà!

CultureInfo culture = new CultureInfo("en-US");
culture.Calendar.TwoDigitYearMax = 2099;

string dateString = "1 Jan 21";
DateTime.TryParse(dateString, culture, DateTimeStyles.None, out var result);
// true, 1/1/2021 12:00:00 AM
Enter fullscreen mode Exit fullscreen mode

Sources: Convert a two digit year, Parse string dates with two digit year

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .