This source file includes following definitions.
- day_num
- leap
- days_last_month
- days_this_month
- days_last_year
- days_this_year
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 #include <limits.h>
27 #include <time.h>
28 #include "gregor.h"
29
30 static const int
31 days_in_month[] = {
32 31,
33 28,
34 31,
35 30,
36 31,
37 30,
38 31,
39 31,
40 30,
41 31,
42 30,
43 31
44 };
45
46 static int leap(int year);
47
48 int
49 day_num(int year, int month, int day)
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 {
68 int dn;
69 int i;
70 int isleap;
71
72
73
74
75 if (year < 1) return - 1;
76
77 if (year > (INT_MAX / 366)) return - 1;
78 if (month > 12 || month < 1) return - 1;
79 if (day < 1) return - 1;
80
81 isleap = leap(year);
82
83 if (month != 2) {
84 if(day > days_in_month[month - 1]) return - 1;
85 }
86 else if ((isleap && day > 29) || (!isleap && day > 28))
87 return - 1;
88
89
90
91
92 i = year - 1;
93
94 dn = (i * 365) + ((i / 4) - (i / 100) + (i / 400));
95
96
97
98 for (i = month - 1; i > 0; --i)
99 dn += days_in_month[i - 1];
100
101 if (month > 2 && isleap) ++dn;
102
103
104
105 dn += day;
106
107 return dn;
108 }
109
110 static int
111 leap(int year)
112
113 {
114
115
116
117 return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
118 }
119
120 int
121 days_last_month (void)
122
123 {
124 struct tm time_record;
125 time_t current_time;
126 time (¤t_time);
127 localtime_r (¤t_time, &time_record);
128
129 switch (time_record.tm_mon) {
130 case 0: return days_in_month[11];
131 case 2: return days_in_month[1] + (leap (time_record.tm_year + 1900) ? 1 : 0);
132 default: return days_in_month[time_record.tm_mon - 1];
133 }
134 }
135
136 int
137 days_this_month (void)
138
139 {
140 struct tm time_record;
141 time_t current_time;
142 time (¤t_time);
143 localtime_r (¤t_time, &time_record);
144
145 switch (time_record.tm_mon) {
146 case 1: return days_in_month[1] + (leap (time_record.tm_year + 1900) ? 1 : 0);
147 default: return days_in_month[time_record.tm_mon];
148 }
149 }
150
151 int
152 days_last_year (void)
153
154 {
155 struct tm time_record;
156 time_t current_time;
157 time (¤t_time);
158 localtime_r (¤t_time, &time_record);
159
160 if (leap(time_record.tm_year - 1 + 1900)) {
161 return 366;
162 }
163
164 return 365;
165 }
166
167 int
168 days_this_year (void)
169
170 {
171 struct tm time_record;
172 time_t current_time;
173 time (¤t_time);
174 localtime_r (¤t_time, &time_record);
175
176 if (leap(time_record.tm_year + 1900)) {
177 return 366;
178 }
179
180 return 365;
181 }