Because of project requirements, the age is calculated based on the time of the day (based on the server time, so do not make a mistake on the server time, if the birthday is full, the day is counted as one year old. That is to say, when the birth time is 0, if you need to change it, just make a few changes.
The function is as follows:
- # Region age Calculation
- /// <Summary>
- /// Calculate the age
- /// </Summary>
- /// <Param name = "Birthday"> Date of Birth </param>
- /// <Returns> </returns>
- Public static int caculateage (string birthday)
- {
- Int iage = 0; // initialize age data
- If (birthday! = "")
- {
- Datetime dtbirthday = datetime. parse (birthday );
- Datetime dtnow = datetime. now;
- If (dtnow. Year> dtbirthday. Year) // the current year is later than the year of birth.
- {
- Iage + = dtnow. Year-dtbirthday. Year-1;
- If (dtnow. Month> dtbirthday. month) // the current month is larger than the month of birth.
- {
- ++ Iage;
- }
- Else if (dtnow. month = dtbirthday. month) // the current month is the same as the month of birth.
- {
- If (dtnow. Day> = dtbirthday. Day) // the current day is larger than the day of birth.
- {
- ++ Iage;
- }
- }
- }
- }
- Return iage;
- }
- # Endregion
The parameter is a string. If you think it is not good, you can change it to datatime. There is no exception handling for strings not in the date format. If you need to add a string, it will be OK.