Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date to Day of the week algorithm?

Tags:

c++

algorithm

What is the algorithm that, given a day, month and year, returns a day of the week?

like image 456
jmasterx Avatar asked Apr 26 '11 23:04

jmasterx


People also ask

What is the formula to find the day of the week of a date?

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!

Why is it called Doomsday rule?

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.

What is the doomsday formula?

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) ...

How does the doomsday method work?

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.


1 Answers

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';
like image 73
Potatoswatter Avatar answered Oct 17 '22 08:10

Potatoswatter