Skip to content

Instantly share code, notes, and snippets.

@hsupu
Created May 27, 2020 13:48
Show Gist options
  • Save hsupu/d783653f44c4b9962a1ea8509cfc831b to your computer and use it in GitHub Desktop.
Save hsupu/d783653f44c4b9962a1ea8509cfc831b to your computer and use it in GitHub Desktop.
公元日期计算
#include <stdio.h>
#include <stdlib.h>
int days_m[] = {
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
};
int leap_year(int y) {
if (y % 400 == 0) return 1;
if (y % 4 == 0) {
if (y % 100 != 0) return 0;
else return 1;
} else return 0;
}
void calc(int days) {
int y = 1;
while (1) {
int days_y = leap_year(y) ? 366 : 365;
if (days < days_y) break;
days -= days_y;
y += 1;
}
int m = 0;
days_m[1] = (leap_year(y)) ? 29 : 28;
for (int i = 0; i < 12; ++i) {
if (days < days_m[i]) break;
days -= days_m[i];
m += 1;
}
printf("y=%d m=%d d=%d\n", y, m, days);
}
int main(int argc, const char* argv[]) {
if (argc <= 1) return -1;
int days = atoi(argv[1]);
calc(days);
return 0;
}
@hsupu
Copy link
Author

hsupu commented Jun 11, 2020

这是不对的,因为历法在中间发生过一次变化,从儒略历变成格里历。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment