private static int CalculateDay(DateTime dateOfBirth) { DateTime today = DateTime.Today; if (today.Day == dateOfBirth.Day) { return 0; } if (today.Day > dateOfBirth.Day) { return today.Day - dateOfBirth.Day; } // based on days in month switch(today.Month - 1) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31 - dateOfBirth.Day + today.Day; case 2: if (today.Year % 4 == 0) { return 29 - dateOfBirth.Day + today.Day; } return 28 - dateOfBirth.Day + today.Day; default: return 30 - dateOfBirth.Day + today.Day; } } private static int CalculateMonth(DateTime dateOfBirth) { DateTime today = DateTime.Today; int monthModifier = 0; // today is the birthday if (today.Day >= dateOfBirth.Day && today.Month == dateOfBirth.Month) { return 0; } // determine the month modifier if (today.Day >= dateOfBirth.Day && today.Month > dateOfBirth.Month) { monthModifier = 0; } else if (today.Day < dateOfBirth.Day && today.Month > dateOfBirth.Month) { monthModifier = -1; } else if (today.Day >= dateOfBirth.Day && today.Month < dateOfBirth.Month) { monthModifier = 12; } else if (today.Day < dateOfBirth.Day && today.Month <= dateOfBirth.Month) { monthModifier = 11; } // calculate number of months int month = today.Month - dateOfBirth.Month + monthModifier; if (month > 0) { return month; } return 0; } private static int CalculateYear(DateTime dateOfBirth) { DateTime today = DateTime.Today; int yearModifier = -1; // determine if current date is after the date of birth this year if ((today.Day >= dateOfBirth.Day && today.Month == dateOfBirth.Month) || (today.Month > dateOfBirth.Month)) { yearModifier = 0; } // calculate the number of years return today.Year - dateOfBirth.Year + yearModifier; }
Usage would look something like:
int month = CalculateMonth(dob); int year = CalculateYear(dob); int day = CalculateDay(dob); string age = "Age: " + year + " year(s) " + month + " month(s) " + day + " day(s)";
No comments:
Post a Comment