How would you calculate the age in C# using date of birth (considering leap years)

前端 未结 6 1866
傲寒
傲寒 2020-12-21 07:02

Here is a problem. I have seen many solutions, but no one seems to be fulfilling the criteria I want...

I want to display the age in this format

20 y         


        
6条回答
  •  猫巷女王i
    2020-12-21 07:16

    write this small function to have the number of leap year days between the current year and the date of birth year and add the returned days to the days part of your age:

     private static int NumberOfLeapYears(int startYear, int endYear)
     {         
     int counter = 0;
     for (int year = startYear; year <= endYear; year++)
     counter += DateTime.IsLeapYear(year) ? 1 : 0;
     return counter;
     } 
    

提交回复
热议问题