Coders Packet

Finding Day From Date in C++

By Kothapally Nehasai

In this C++ program, we will find the day(Monday-Sunday) from the input Date. According to ISO 8601 standards calendar, the week begins with 1 as for Monday and ends with 7 for Sunday.

How Algorithm Works:

Some months start on the same day(like Jan and Oct, Feb Mar and Nov, April and July during leap years, and Jan Apr and July, Feb and Aug, Mar and Nov during leap years). Now let's make an array containing the first days of all the months according to the first month of January i.e.{0,3,3,6,1,4,6,2,5,0,3,5}. we derived this by taking mod of no of days with no of weeks to get the no of days left. For example, if we assume that January 1st was on Sunday, then to know February 1st: 7*4+3. so the day on the first February will be 3 days followed by the first day of January.

For finding the day with the given date, we have a formula,
(dd+mm+yyyy+[yyyy/4]+c)mod 7
where dd stands for the day, mm stands for the month, yyyy stands for the year and c stands for the century number. Here we mathematically adjust for the leap year. Adding one extra day after every 4th year except the 100th year and adding the 400th year, Hence we replace yyyy with (yyyy + yyyy/4 - yyyy/100 + yyyy/400). where yyyy is the year.

Here yyyy = yyyy-1 for mm<3 is a trick where it creates a virtual year that starts on March 1st and ends on February 28(or 29). we are subtracting 1 from the year for non-leap years too. so there is a blank day between February 28 and March 1, To adjust this we subtract 1 from the t[] values of every month after February. so t[] becomes {0,3,2,5,0,3,5,1,4,6,2,4}.C++ Output for Module 2

 

Download project

Reviews Report

Submitted by Kothapally Nehasai (Neha1292)

Download packets of source code on Coders Packet