For a given month or so, a formula is the day of the week

Source: Internet
Author: User

Look at the formula:


int caculateweekday (int y,int m, int d) {    if (m==1| | m==2) {        m+=12;        y--;    }    int iweek= (d+2*m+3* (m+1)/5+y+y/4-y/100+y/400)%7;  



This formula is called Kimlarsson formula.

The formula is derived from the beginning of January 1, 00 A.D.

Just look very complicated, I analyze each:

Iweek= (d+2*m+3* (m+1)/5+y+y/4-y/100+y/400)%7


1.

(D+2*m+3* (m+1)/5+y+y/4-y/100+y/400)%7

D represents the number of days, the number of days to 7 modulo, this good understanding


2.

(d+2*m+3* (m+1)/5+y+y/4-y/100+y/400)%7

Regardless of the Swiss year, it is 365 days per day. Since 365 is 7 of 52 times times more than 1 days, all plus y

3.

(d+2*m+3* (m+1)/5+y+y/4-y/100+y/400)%7


if a leap year is considered, due to leap years bipin more than one day,

y/4-y/100+y/400

The formula represents how many days a leap year is in Y (including y) years ago


4.

(d+2*m+3* (m+1)/5+y+y/4-y/100+y/400)%7


Because the number of days in each month is different, it facilitates the mapping of the formula, which sees January and February as 1 March and 1 April

Some people will ask why the 1, February as 13, 1 April Now, why is not it?

Because only the days of February are changing with the year of the leap years, and if the March changes with common year and leap, then move the 13,14,15 to the back of the month

To ask why?

Look at the following table:

Monthly Error Cumulative modulus 7
3 3 0 0
4 2 3 3
5 3 5 5
6 2 8 1
7 3 3
8 3 6
9 2 2
3 4
2 0
3 of 2
3 5
14-29 1

It was found that the February error was not calculated, so it solved the consistency of the change of the February days and the whole year.


As for this formula:

2*m+3* (m+1)/5

In fact, it is a mapping of the formula 7, you try, all the month size can be mapped to modulo 7

You can also use an array to store modulo 7, and then use the subscript to call

But the formula is a little more useful.



For a given month or so, a formula is the day of the week

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.