Convert a two digit year to a four digit year

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

    If you calculate for a person he will probably not be more than 100 years...

    Eg: 751212

    var nr = "751212";
    var century = DateTime.Now.AddYears(-100).Year.ToString().Substring(0, 2);
    
    var days = (DateTime.Now - DateTime.Parse(century + nr)).Days;
    decimal years = days / 365.25m;
    if(years>=99)
     century = DateTime.Now.Year.ToString().Substring(0, 2);
    
    var fullnr = century+nr;
    

提交回复
热议问题