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.
- Years — That have passed
- Months — That have passed
- Days — That have passed (negative value if the date has still to come in this month).
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace FindingBirthday {
- class Program {
- static void Main(string[] args) {
-
- int year = 0, month = 0, date = 0;
-
-
- Console.WriteLine("How many years have passed?");
- year = Convert.ToInt32(Console.ReadLine());
-
- Console.WriteLine("How many months have passed?");
- month = Convert.ToInt32(Console.ReadLine());
-
- Console.WriteLine("How many days have passed?");
- date = Convert.ToInt32(Console.ReadLine());
-
-
- Console.WriteLine(
- String.Format("Your birthday was on {0}",
- DateTime.Now
- .AddYears(-year)
- .AddMonths(-month)
- .AddDays(-date)
- .ToString("MMMM dd, yyyy on dddd")
- ));
-
-
- Console.Read();
- }
- }
- }
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.