Summary
In this post, I will introduce some problems related to date.
Details
Is Leap Year
bool is_leap(int y) {
if (y % 400 == 0) {
return true;
} else if (y % 100 == 0) {
return false;
} else {
return y % 4 == 0;
}
}
Days of the Year
vector<int> days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int day_of_year(string date) {
// date: "1900-12-21"
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 2));
int day = stoi(date.substr(8, 2));
int result = 0;
for (int m = 1; m < month; ++m) {
result += days[m];
if (m == 2 && is_leap(year)) {
result++;
}
}
result += day;
return result;
}
Days from 1900
int day_since_1900(string date) {
// date: "1900-12-21"
int year = stoi(date.substr(0, 4));
int result = 0;
for (int y = 1900; y < year; ++y) {
result += is_leap(y) ? 366 : 365;
}
result += day_of_year(date);
return result;
}
Days Between Dates
int daysBetweenDates(string date1, string date2) {
return abs(day_since_1900(date1) - day_since_1900(date2));
}