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.
Examples:
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With