-
Notifications
You must be signed in to change notification settings - Fork 0
/
date_conversion2.c
33 lines (28 loc) · 1.06 KB
/
date_conversion2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "date_conversion.h"
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
/* day_of_year:将月和日转换为指定年份的第几天,如果参数值非法则返回-1 */
int day_of_year(int year, int month, int day) {
int i, leap;
leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
if (year < 0 || month < 1 || month > 12 || day < 1 || day > daytab[leap][month])
return -1;
for (i = 1; i < month; ++i)
day += daytab[leap][i];
return day;
}
/* month_day:将指定年份的第几天转换为月和日,如果参数值非法则返回-1, -1 */
void month_day(int year, int yearday, int *pmonth, int *pday) {
int i, leap;
leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
if (year < 0 || yearday < 1 || yearday > (leap ? 366 : 365)) {
*pmonth = *pday = -1;
return;
}
for (i = 1; yearday > daytab[leap][i]; ++i)
yearday -= daytab[leap][i];
*pmonth = i;
*pday = yearday;
}