What is the algorithm that, given a day, month and year, returns a day of the week?
Take the last two digits of the year. Add to that one–quarter of those two digits (discard any remainder). Divide the sum by 7. The remainder is the day of the week!
The Doomsday rule is a method devised by John Conway for computing the day of the week of any given date. The method is based on first computing Doomsday, which is the day of the week of the last day of February. First of all, we need a method of numbering the days of the week.
Applying the Doomsday algorithm involves three steps: Determination of the anchor day for the century, calculation of the anchor day for the year from the one for the century, and selection of the closest date out of those that always fall on the doomsday, e.g., 4/4 and 6/6, and count of the number of days (modulo 7) ...
Find the doomsday of the year using the doomsday algorithm. This involves first finding an anchor day for the century, then using the last two digits of the century to find the number of days () that the anchor day must be shifted by to determine the doomsday for the year.
This can be done using the std::mktime
and std::localtime
functions. These functions are not just POSIX, they are mandated by the C++ Standard (C++03 §20.5).
#include <ctime>
std::tm time_in = { 0, 0, 0, // second, minute, hour
4, 9, 1984 - 1900 }; // 1-based day, 0-based month, year since 1900
std::time_t time_temp = std::mktime( & time_in );
// the return value from localtime is a static global - do not call
// this function from more than one thread!
std::tm const *time_out = std::localtime( & time_temp );
std::cout << "I was born on (Sunday = 0) D.O.W. " << time_out->tm_wday << '\n';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With