I'm currently working on a school project for which I've met the requirements, but I want to challenge myself. How can I accurately display my age in the following format based on today's date/time?
Age: 27 Years -or- Days -or- Hours -or- Seconds (Accounting for Leap Year)
Research I did: How would you calculate the age in C# using date of birth (considering leap years)
I'm more so looking for the math behind it. Here's the math I'm currently using but it's only accurate to 16hr or 960 minutes or 57,600 seconds.
// Tried using "double" datatype, still same problem.
int years = DateTime.Now.Year - dateBirthDate.Year;
int days = (years / 4) + (years * 365);
int hours = (days * 24) + DateTime.Now.Hour;
int minutes = hours * 60;
int seconds = (minutes * 60) + ((DateTime.Now.Hour * 60) * 60) + DateTime.Now.Second;
Should be showing close to 0.
Output:
Thank you Mat, what is your date of birth? Feel free to include the time you were born. 09/08/2018 5:11pm
Years :0
Days :0
Minutes :1020
Seconds :122425
#UPDATE #1
I've managed to get the code partially working but have discovered another unforseen issue. Now it will not account for birthdays that have yet to come. Thoughts?
//Needed casting so I could remove the decimals.
TimeSpan span = DateTime.Now.Subtract(dateBirthDate);
int years = (int)span.Days/365;
int months = years * 12;
int days = (int)span.TotalDays;
int hours = (int)span.TotalHours;
int minutes = (int)span.TotalMinutes;
int seconds = (int)span.TotalSeconds;