You might have usually created applications for evaluating and calculating the age of people using their date of birth. In this post I will teach how you can perform the math to find the birthday of a person.

Required input

For this program to run and find the birthday we require three inputs.

Then we can pass those values to the AddDays, AddMonths, AddYears functions of DateTime to find the birthday.

Code

I used the following code to perform this function.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace FindingBirthday {
  7. class Program {
  8. static void Main(string[] args) {
  9. // Create variables
  10. int year = 0, month = 0, date = 0;
  11. // Get the values
  12. Console.WriteLine("How many years have passed?");
  13. year = Convert.ToInt32(Console.ReadLine());
  14. Console.WriteLine("How many months have passed?");
  15. month = Convert.ToInt32(Console.ReadLine());
  16. Console.WriteLine("How many days have passed?");
  17. date = Convert.ToInt32(Console.ReadLine());
  18. // Do the math and write it!
  19. Console.WriteLine(
  20. String.Format("Your birthday was on {0}",
  21. DateTime.Now // Get current instance of time
  22. .AddYears(-year) // Add years
  23. .AddMonths(-month) // Add months
  24. .AddDays(-date) // Add days
  25. .ToString("MMMM dd, yyyy on dddd") // Format it
  26. ));
  27. // Just for sake of pausing the Console
  28. Console.Read();
  29. }
  30. }
  31. }
The above code performs the action required and finds the date of birth.

Result

For my input, the result was August 29, 1995 on Tuesday. Which is my date of birth calculated from my input of years, months and days that have passed since my birth.