The vs2010 test passed, the main idea is to calculate the age (year, month, and day) from the date of birth and the current date, two dates.
using System; using ; using ; namespace PublicClass { public static class CalculationDate { /// <summary> /// Calculate age (years, month, and day) from two dates /// </summary> public static void calculationDate(DateTime beginDateTime, DateTime endDateTime) { if (beginDateTime > endDateTime) throw new Exception("The start time should be less than or equal to the end time!"); /* Calculate the total number of months from the date of birth to the current date*/ int Months = - + 12 * ( - ); /*After the date of birth is added to the total number of months, if it is greater than the current date, it will be reduced by one month*/ int totalMonth = ((Months) > endDateTime) ? Months - 1 : Months; /*Calculate the whole year*/ int fullYear = totalMonth / 12; /*Calculate the whole month*/ int fullMonth = totalMonth % 12; /*Count the number of days*/ DateTime changeDate = (totalMonth); double days = (endDateTime - changeDate).TotalDays; } } }
A little simpler:
public int CalculateAgeCorrect(DateTime birthDate, DateTime now) { int age = - ; if ( < || ( == && < )) age--; return age; }
Let's take a look at the general method:
Method 1:
string m_Str = "1984-04-04"; int m_Y1 = (m_Str).Year; int m_Y2 = ; int m_Age = m_Y2 - m_Y1; (m_Age);
Method 2:
If you format the date as yyyymmdd, subtract the birthday from the current day and remove 4 numbers in the end, you will get the age :)
I believe that such a method can be implemented in any language:
20080814-19800703=280111
Remove the last 4 digits = 28.
int now =(("yyyyMMdd")); int dob =(("yyyyMMdd")); string dif =(now - dob).ToString(); string age ="0"; if(>4) age = (0, -4);
Method 3:
DateTime now =; int age = - ; if(bday > (-age)) age--;
The above is all about this article, and I hope it will be helpful to everyone to learn C#.