TIL: How to convert 2-digit year to 4-digit year in C#24 Feb 2021 #todayilearned #csharp
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, though.
To convert 2-digit year into a 4-digit year, use the ToFourDigitYear method inside your current culture’s calendar.
CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(21) // 2021
But, if you’re working with a string containing a date, create a custom
CultureInfo instance and set the maximum year to 2099. After that, 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