Reputation: 300
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).
Upvotes: 4
Views: 1202
Reputation: 26209
I do not think that ParseExact
can do your job, so here my version with conditional blocks
but works.
Try This:
DateTime currentDate = DateTime.Now;
String strDate = "01/01/41";
DateTime userDate=DateTime.ParseExact(strDate, "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);
currentDate=currentDate.AddYears(30);
if ((userDate.Year%100) > (currentDate.Year%100))
{
strDate = strDate.Insert(6, "19");
}
else
{
strDate = strDate.Insert(6, "20");
}
DateTime newUserDate = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Upvotes: 0
Reputation: 113472
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);
Upvotes: 7