Convert a two digit year to a four digit year

前端 未结 17 983
误落风尘
误落风尘 2020-12-25 12:13

This is a question of best practices. I have a utility that takes in a two digit year as a string and I need to convert it to a four digit year as a string. right now I do <

17条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-25 12:53

    This solution we use for Expiration Dates, the user enters MM and YY into separate fields. This results in dates being the 31st or 30th and 28th or 29th also for February.

    /// 
    /// Creates datetime for current century and sets days to end of month
    /// 
    /// 
    /// 
    /// 
    public static DateTime GetEndOfMonth(string MM, string YY)
    {
        // YY -> YYYY #RipVanWinkle
        // Gets Current century and adds YY to it.
        // Minus 5 to allow dates that may be expired to be entered.
        // eg. today is 2017, 12 = 2012 and 11 = 2111
        int currentYear = DateTime.Now.Year;
        string thisYear = currentYear.ToString().Substring(0, 2) + YY;
        int month = Int32.Parse(MM);
        int year = Int32.Parse(thisYear);
        if ((currentYear - 5) > year)
            year += 100;
    
        return new DateTime(year, month, DateTime.DaysInMonth(year, month));
    }
    

提交回复
热议问题