C#DateTime.ParseExact确定年前缀

时间:2013-12-03 03:54:09

标签: c# date datetime

我要求解析“dd / MM / yy”形式的日期字符串,这样如果认为年份比当前年份大30年,那么它将在年份前加上19。例如,它以20为前缀。

示例:

01/01/50 - > 01/01/1950
01/01/41 - > 2041年1月1日

我不确定DateTime.ParseExact如何决定它应该使用什么前缀,或者我如何以某种方式强制它(它似乎做出了明智的假设,如01/01/12 - > 01/01 / 2012,我只是不知道如何决定它将转换的点。)

2 个答案:

答案 0 :(得分:6)

使用Calendar.TwoDigitYearMax属性。

  

获取或设置可以表示的100年范围的最后一年   按两位数的年份。

在你的情况下,这样的事情会起作用:

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

答案 1 :(得分:0)

我认为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);