C # DateTime.ParseExact specifying a year prefix

I have a requirement regarding parsing date strings in the form "dd / MM / yy", so if the year is considered more than 30 years from the current year, then it will be the prefix of year 19. In another instance it has the prefix 20.

Examples:

01/01/50 → 01/01/1950
01/01/41 → 01/01/2041

I'm not sure how DateTime.ParseExact determines which prefix it should use, or how I can force it anyway (it seems to make a reasonable assumption like 01/01/12 → 01/01/2012, I just don't know how to dictate the point at which it will switch).

+4
source share
2 answers

Use property Calendar.TwoDigitYearMax.

100- , 2- .

- :

// 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);
+6

, ParseExact , conditional blocks .

:

            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);
0

All Articles