Convert a two digit year to a four digit year

前端 未结 17 963
误落风尘
误落风尘 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:44

    Had a similar issue, and came up with this... HTH!

    value = this.GetDate()
    
    if (value.Length >= 6)//ensure that the date is mmddyy
    {
        int year = 0;
    
        if (int.TryParse(value.Substring(4, 2), out year))
        {
            int pastMillenium = int.Parse(DateTime.Now.ToString("yyyy").Substring(0, 2)) - 1;
    
            if (year > int.Parse(DateTime.Now.ToString("yy")))//if its a future year it's most likely 19XX
            {
                value = string.Format("{0}{1}{2}", value.Substring(0, 4), pastMillenium, year.ToString().PadLeft(2, '0'));
            }
            else
            {
                value = string.Format("{0}{1}{2}", value.Substring(0, 4), pastMillenium + 1, year.ToString().PadLeft(2, '0'));
            }
        }
        else
        {
            value = string.Empty;
        }
    }
    else
    {
        value = string.Empty;
    }
    

提交回复
热议问题