Search code examples
c#.netdatetimecalc

How to get DateOfBirth using age in c#?


I have user age, month and day something like 18 year 2 month and 5 days. I need to return user DateOfBirth using these params. How can I find user DateOfBirth from year, month and day?


Solution

  • I've found a solution and it's works for me.

     public static DateTime GetDateOfBirth(int year, int month, int day)
        {
            var today = DateTime.Today;
            int currentYear = today.Year;
            int currentDay = today.Day;
            int currentMonth = today.Month;
    
            if (day >= currentDay)
            {
                currentMonth--;
                currentDay += DateTime.DaysInMonth(currentYear, currentMonth);
            }
    
            if (month >= currentMonth)
            {
                currentMonth += 12;
                currentYear--;
            }
    
            return new DateTime(currentYear - year, currentMonth - month, currentDay - day);
        }