Logo Questions Linux Laravel Mysql Ubuntu Git Menu

C# DateTime.ParseExact determining year prefix





I have a requirement regarding the parsing of date strings of the form "dd/MM/yy" such that if the year is deemed greater than 30 years from the current year then it would prefix the year with 19. In the other instance it is prefixed with 20.


01/01/50 -> 01/01/1950
01/01/41 -> 01/01/2041

I'm not sure how DateTime.ParseExact decides what prefix it should use or how I can force it one way or the other (it does appear to make a sane assumption as 01/01/12 -> 01/01/2012, I just don't know how to dictate the point at which it will switch).

like image 686
Troy Patrick Avatar asked Mar 22 '23 10:03

Troy Patrick

1 Answers

Use the Calendar.TwoDigitYearMax property.

Gets or sets the last year of a 100-year range that can be represented by a 2-digit year.

In your case, something like this would work:

// Setup 
var cultureInfo = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
var calendar = cultureInfo.Calendar;
calendar.TwoDigitYearMax = DateTime.Now.Year + 30;
cultureInfo.DateTimeFormat.Calendar = calendar;

// Parse
var _1950 = DateTime.ParseExact("01/01/50", "dd/MM/yy", cultureInfo);
var _2041 = DateTime.ParseExact("01/01/41", "dd/MM/yy", cultureInfo);
like image 98
Ani Avatar answered Apr 06 '23 04:04