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.

  1. Years — That have passed
  2. Months — That have passed
  3. 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)
        {
           // Create variables
           int year = 0, month = 0, date = 0;

           // Get the values
           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());

           // Do the math and write it!
           Console.WriteLine(
               String.Format("Your birthday was on {0}",
               DateTime.Now // Get current instance of time
               .AddYears(-year) // Add years
               .AddMonths(-month) // Add months
               .AddDays(-date) // Add days
               .ToString("MMMM dd, yyyy on dddd") // Format it
               )
           );

           // Just for sake of pausing the Console
           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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s