How to Calculate Birthday from Year, Month and Date

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

Ebook Download
View all
Learn
View all