Kim Larson formula for converting dates to days of the week

Method 1: Kim Larson's formula

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

  • d is the date, the range is 1-31
  • m is the month, the range is 3-14, January and February of the current year need to be processed as the 13th and 14th month of the previous year
  • y is the year, when the month is 1, 2, y needs to be reduced by one
  • The result is 0-6, Sunday is represented by 0, Monday is 1, and so on, Saturday is 6

Method 2: Add 1 day each time to the target date

#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

string months[13] = {
    
    " ","January","February","March","April","May","June","July","August","September","October","November","December"};
unordered_map<string, int> map_month;
string map_day[8] = {
    
    " ","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
int month_day[2][13] = {
    
    
    {
    
    0,31,28,31,30,31,30,31,31,30,31,30,31}, //common year
    {
    
    0,31,29,31,30,31,30,31,31,30,31,30,31}  //leap year
};

int leap(int year);
bool dayJudge(int day1, int month1, int year1, int day2, int month2, int year2);
void printDay(int day, int month, int year);

int main(){
    
    
    for(int i=1; i<=12; i++) map_month[months[i]] = i;
    int day, year;
    string month;
    while(cin>>day>>month>>year){
    
    
        printDay(day, map_month[month], year);
    }
    return 0;
}

int leap(int year){
    
    
    if((year%4==0 && year%100!=0) || year%400==0) return 1;
    else return 0;
}

bool dayJudge(int day1, int month1, int year1, int day2, int month2, int year2){
    
    
    if(year1!=year2) return year1>year2;
    else if(month1!=month2) return month1>month2;
    else return day1>day2;
}

void printDay(int day, int month, int year){
    
    
    //以2001年10月9日是星期2为基准
    int base_day=9, base_month=10, base_year=2001;
    bool later = true;
    if(dayJudge(base_day, base_month, base_year, day, month, year)){
    
    
        swap(base_day, day);
        swap(base_month, month);
        swap(base_year, year);
        later = false;
    }
    int day_gap = 0;
    while(base_year!=year || base_month!=month || base_day!=day){
    
    
        base_day++;
        if(base_day>month_day[leap(base_year)][base_month]){
    
    
            base_month++;
            base_day = 1;
        }
        if(base_month>12){
    
    
            base_year++;
            base_month = 1;
        }
        day_gap++;
    }
    day_gap %= 7;
    int ans = later ? (day_gap<=5 ? 2+day_gap : day_gap-5) : (day_gap<=1 ? 2-day_gap : 9-day_gap);
    cout<<map_day[ans]<<endl;
    return;
}

Guess you like

Origin blog.csdn.net/sinat_37517996/article/details/105392093
Kim