Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I need to convert how many 'days Old' someone is (e.g. 3 years old = 1,095 days old) to a 'date of birth' answer i.e. dd/MM/yyyy. I have tried many different ways how to do this, but to no avail (yet) - e.g. using a mathematical formula but it gets a bit complicated, especially when considering how to implement that into C# (for a beginner, at least).

What is in the box below is one of the many ways I have tried thus far. I know it's wrong but it's one of many of my attempts. What is the simplest way to go about this (assuming 1 year is 365 days, if the computer doesn't have it's own automated calculation to include leap years)?

Finally, if I am to include leap years, would the adjustment to simply be to take into consideration that 1 year = 365.25 years? Or would there be more complexity to this?

Kind regards.

What I have tried:

public static string GetBirthDate(int daysOld)
{
    var dateToday = Convert.ToInt32(DateTime.Now);

    var calc = (dateToday - 365.25 * daysOld);

    return Convert.ToString(calc);
}
Posted
Updated 14-Jul-17 3:24am
v2

If I were doing something like this, I would do it like this:
C#
public static DateTime(int days)
{
  return new DateTime.Now.Subtract(TimeSpan.FromDays(days));
}
 
Share this answer
 
Comments
Richard Deeming 14-Jul-17 9:30am    
You'll need a function name in there! :)
Pete O'Hanlon 14-Jul-17 10:05am    
It's in there, but only if you can read subatomic :)
int daysOld = 1095;
DateTime dob = DateTime.Now.AddDays(daysOld * -1);
 
Share this answer
 
C#
public static string GetBirthDate(int daysOld)
{
    // DateTime.Now.AddDays(-daysOld).To... has many format options
    // beware AddDays: daysOld conversion to type double

    return DateTime.Now.AddDays(-daysOld).ToString("dd'/'MM'/'yyyy")
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900