Skip to content

Instantly share code, notes, and snippets.

@magicsih
Created May 30, 2017 07:20
Show Gist options
  • Save magicsih/699dc3479b8a7c60e3ce9cf71fd74afe to your computer and use it in GitHub Desktop.
Save magicsih/699dc3479b8a7c60e3ce9cf71fd74afe to your computer and use it in GitHub Desktop.
How to know what day January first is.
#include <ctime>
#include <stdio.h>
#include <iostream>
using namespace std;
bool is_leap_year(int year);
int get_wday_january_first(int yday, int wday);
int main()
{
string week_names[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
int weeks[30] = {
6, 1, 2, 3, 4 //2000 Sat, 2001 Mon, 2002 Tue 2003 Wed, 2004 Thu
, 6, 0, 1, 2, 4
, 5, 6, 0, 2, 3
, 4, 5, 0, 1, 2
, 3, 5, 6, 0, 1 // 2020 Wed, 2021 Fri, 2022 Sat, 2023 Sun, 2024 Mon
, 3, 4, 5, 6, 1 // 2025
};
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
int startYear = 2000;
int endYear = startYear + (sizeof(weeks) / sizeof(weeks[0]));
for (int y = startYear; y < endYear; y++) {
int m = 5;
int d = 28;
timeinfo->tm_year = y - 1900;
timeinfo->tm_mon = m - 1;
timeinfo->tm_mday = d;
mktime(timeinfo);
int wday = timeinfo->tm_wday; // weekday
int yday = timeinfo->tm_yday; // days of year
int year = timeinfo->tm_year + 1900;
int wday_jf = get_wday_january_first(yday, wday);
if (wday_jf != weeks[year - startYear]) {
cout << "[X] ";
}
else{
cout << "[O] ";
}
cout << year << " (" << (is_leap_year(year) ? "leap" : "comm") << ") January, 1st is " << "Expected:" << week_names[weeks[year - startYear]].c_str() << "(" << weeks[year - startYear] << ")" << " Result:" << week_names[wday_jf].c_str() << "(" << wday_jf << ")" << endl;
}
return 0;
}
int get_wday_january_first(int yday, int wday) {
int wday_jf = wday - (yday % 7);
if (wday_jf < 0) wday_jf = 7 + wday_jf;
return wday_jf;
}
bool is_leap_year(int year) {
if ((year % 4) == 0){
if ((year % 100) == 0) {
if ((year % 400) == 0) {
return true;
}
else{
return false;
}
}
else{
return true;
}
}
else{
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment