xref: /PHP-8.1/ext/date/lib/tm2unixtime.c (revision 4a520229)
1 /*
2  * The MIT License (MIT)
3  *
4  * Copyright (c) 2015-2019 Derick Rethans
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "timelib.h"
26 #include "timelib_private.h"
27 
28 /*                                    dec  jan  feb  mrt  apr  may  jun  jul  aug  sep  oct  nov  dec */
29 static int days_in_month_leap[13] = {  31,  31,  29,  31,  30,  31,  30,  31,  31,  30,  31,  30,  31 };
30 static int days_in_month[13]      = {  31,  31,  28,  31,  30,  31,  30,  31,  31,  30,  31,  30,  31 };
31 
do_range_limit(timelib_sll start,timelib_sll end,timelib_sll adj,timelib_sll * a,timelib_sll * b)32 static void do_range_limit(timelib_sll start, timelib_sll end, timelib_sll adj, timelib_sll *a, timelib_sll *b)
33 {
34 	if (*a < start) {
35 		*b -= (start - *a - 1) / adj + 1;
36 		*a += adj * ((start - *a - 1) / adj + 1);
37 	}
38 	if (*a >= end) {
39 		*b += *a / adj;
40 		*a -= adj * (*a / adj);
41 	}
42 }
43 
inc_month(timelib_sll * y,timelib_sll * m)44 static void inc_month(timelib_sll *y, timelib_sll *m)
45 {
46 	(*m)++;
47 	if (*m > 12) {
48 		*m -= 12;
49 		(*y)++;
50 	}
51 }
52 
dec_month(timelib_sll * y,timelib_sll * m)53 static void dec_month(timelib_sll *y, timelib_sll *m)
54 {
55 	(*m)--;
56 	if (*m < 1) {
57 		*m += 12;
58 		(*y)--;
59 	}
60 }
61 
do_range_limit_days_relative(timelib_sll * base_y,timelib_sll * base_m,timelib_sll * y,timelib_sll * m,timelib_sll * d,timelib_sll invert)62 static void do_range_limit_days_relative(timelib_sll *base_y, timelib_sll *base_m, timelib_sll *y, timelib_sll *m, timelib_sll *d, timelib_sll invert)
63 {
64 	timelib_sll leapyear;
65 	timelib_sll month, year;
66 	timelib_sll days;
67 
68 	do_range_limit(1, 13, 12, base_m, base_y);
69 
70 	year = *base_y;
71 	month = *base_m;
72 
73 /*
74 	printf( "S: Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days);
75 */
76 	if (!invert) {
77 		while (*d < 0) {
78 			dec_month(&year, &month);
79 			leapyear = timelib_is_leap(year);
80 			days = leapyear ? days_in_month_leap[month] : days_in_month[month];
81 
82 			/* printf( "I  Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days); */
83 
84 			*d += days;
85 			(*m)--;
86 		}
87 	} else {
88 		while (*d < 0) {
89 			leapyear = timelib_is_leap(year);
90 			days = leapyear ? days_in_month_leap[month] : days_in_month[month];
91 
92 			/* printf( "I  Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days); */
93 
94 			*d += days;
95 			(*m)--;
96 			inc_month(&year, &month);
97 		}
98 	}
99 	/*
100 	printf( "E: Y%d M%d   %d %d %d   %d\n", year, month, *y, *m, *d, days);
101 	*/
102 }
103 
do_range_limit_days(timelib_sll * y,timelib_sll * m,timelib_sll * d)104 static int do_range_limit_days(timelib_sll *y, timelib_sll *m, timelib_sll *d)
105 {
106 	timelib_sll leapyear;
107 	timelib_sll days_this_month;
108 	timelib_sll last_month, last_year;
109 	timelib_sll days_last_month;
110 
111 	/* can jump an entire leap year period quickly */
112 	if (*d >= DAYS_PER_ERA || *d <= -DAYS_PER_ERA) {
113 		*y += YEARS_PER_ERA * (*d / DAYS_PER_ERA);
114 		*d -= DAYS_PER_ERA * (*d / DAYS_PER_ERA);
115 	}
116 
117 	do_range_limit(1, 13, 12, m, y);
118 
119 	leapyear = timelib_is_leap(*y);
120 	days_this_month = leapyear ? days_in_month_leap[*m] : days_in_month[*m];
121 	last_month = (*m) - 1;
122 
123 	if (last_month < 1) {
124 		last_month += 12;
125 		last_year = (*y) - 1;
126 	} else {
127 		last_year = (*y);
128 	}
129 	leapyear = timelib_is_leap(last_year);
130 	days_last_month = leapyear ? days_in_month_leap[last_month] : days_in_month[last_month];
131 
132 	if (*d <= 0) {
133 		*d += days_last_month;
134 		(*m)--;
135 		return 1;
136 	}
137 	if (*d > days_this_month) {
138 		*d -= days_this_month;
139 		(*m)++;
140 		return 1;
141 	}
142 	return 0;
143 }
144 
do_adjust_for_weekday(timelib_time * time)145 static void do_adjust_for_weekday(timelib_time* time)
146 {
147 	timelib_sll current_dow, difference;
148 
149 	current_dow = timelib_day_of_week(time->y, time->m, time->d);
150 	if (time->relative.weekday_behavior == 2)
151 	{
152 		/* To make "this week" work, where the current DOW is a "sunday" */
153 		if (current_dow == 0 && time->relative.weekday != 0) {
154 			time->relative.weekday -= 7;
155 		}
156 
157 		/* To make "sunday this week" work, where the current DOW is not a
158 		 * "sunday" */
159 		if (time->relative.weekday == 0 && current_dow != 0) {
160 			time->relative.weekday = 7;
161 		}
162 
163 		time->d -= current_dow;
164 		time->d += time->relative.weekday;
165 		return;
166 	}
167 	difference = time->relative.weekday - current_dow;
168 	if ((time->relative.d < 0 && difference < 0) || (time->relative.d >= 0 && difference <= -time->relative.weekday_behavior)) {
169 		difference += 7;
170 	}
171 	if (time->relative.weekday >= 0) {
172 		time->d += difference;
173 	} else {
174 		time->d -= (7 - (abs(time->relative.weekday) - current_dow));
175 	}
176 	time->relative.have_weekday_relative = 0;
177 }
178 
timelib_do_rel_normalize(timelib_time * base,timelib_rel_time * rt)179 void timelib_do_rel_normalize(timelib_time *base, timelib_rel_time *rt)
180 {
181 	do_range_limit(0, 1000000, 1000000, &rt->us, &rt->s);
182 	do_range_limit(0, 60, 60, &rt->s, &rt->i);
183 	do_range_limit(0, 60, 60, &rt->i, &rt->h);
184 	do_range_limit(0, 24, 24, &rt->h, &rt->d);
185 	do_range_limit(0, 12, 12, &rt->m, &rt->y);
186 
187 	do_range_limit_days_relative(&base->y, &base->m, &rt->y, &rt->m, &rt->d, rt->invert);
188 	do_range_limit(0, 12, 12, &rt->m, &rt->y);
189 }
190 
magic_date_calc(timelib_time * time)191 static void magic_date_calc(timelib_time *time)
192 {
193 	timelib_sll y, ddd, mi, mm, dd, g;
194 
195 	/* The algorithm doesn't work before the year 1 */
196 	if (time->d < -719498) {
197 		return;
198 	}
199 
200 	g = time->d + HINNANT_EPOCH_SHIFT - 1;
201 
202 	y = (10000 * g + 14780) / 3652425;
203 	ddd = g - ((365*y) + (y/4) - (y/100) + (y/400));
204 	if (ddd < 0) {
205 		y--;
206 		ddd = g - ((365*y) + (y/4) - (y/100) + (y/400));
207 	}
208 	mi = (100 * ddd + 52) / 3060;
209 	mm = ((mi + 2) % 12) + 1;
210 	y = y + (mi + 2) / 12;
211 	dd = ddd - ((mi * 306 + 5) / 10) + 1;
212 	time->y = y;
213 	time->m = mm;
214 	time->d = dd;
215 }
216 
timelib_do_normalize(timelib_time * time)217 void timelib_do_normalize(timelib_time* time)
218 {
219 	if (time->us != TIMELIB_UNSET) do_range_limit(0, 1000000, 1000000, &time->us, &time->s);
220 	if (time->s != TIMELIB_UNSET) do_range_limit(0, 60, 60, &time->s, &time->i);
221 	if (time->s != TIMELIB_UNSET) do_range_limit(0, 60, 60, &time->i, &time->h);
222 	if (time->s != TIMELIB_UNSET) do_range_limit(0, 24, 24, &time->h, &time->d);
223 	do_range_limit(1, 13, 12, &time->m, &time->y);
224 
225 	/* Short cut if we're doing things against the Epoch */
226 	if (time->y == 1970 && time->m == 1 && time->d != 1) {
227 		magic_date_calc(time);
228 	}
229 
230 	do {} while (do_range_limit_days(&time->y, &time->m, &time->d));
231 	do_range_limit(1, 13, 12, &time->m, &time->y);
232 }
233 
do_adjust_relative(timelib_time * time)234 static void do_adjust_relative(timelib_time* time)
235 {
236 	if (time->relative.have_weekday_relative) {
237 		do_adjust_for_weekday(time);
238 	}
239 	timelib_do_normalize(time);
240 
241 	if (time->have_relative) {
242 		time->us += time->relative.us;
243 
244 		time->s += time->relative.s;
245 		time->i += time->relative.i;
246 		time->h += time->relative.h;
247 
248 		time->d += time->relative.d;
249 		time->m += time->relative.m;
250 		time->y += time->relative.y;
251 	}
252 
253 	switch (time->relative.first_last_day_of) {
254 		case TIMELIB_SPECIAL_FIRST_DAY_OF_MONTH: /* first */
255 			time->d = 1;
256 			break;
257 		case TIMELIB_SPECIAL_LAST_DAY_OF_MONTH: /* last */
258 			time->d = 0;
259 			time->m++;
260 			break;
261 	}
262 
263 	timelib_do_normalize(time);
264 }
265 
do_adjust_special_weekday(timelib_time * time)266 static void do_adjust_special_weekday(timelib_time* time)
267 {
268 	timelib_sll count, dow, rem;
269 
270 	count = time->relative.special.amount;
271 	dow = timelib_day_of_week(time->y, time->m, time->d);
272 
273 	/* Add increments of 5 weekdays as a week, leaving the DOW unchanged. */
274 	time->d += (count / 5) * 7;
275 
276 	/* Deal with the remainder. */
277 	rem = (count % 5);
278 
279 	if (count > 0) {
280 		if (rem == 0) {
281 			/* Head back to Friday if we stop on the weekend. */
282 			if (dow == 0) {
283 				time->d -= 2;
284 			} else if (dow == 6) {
285 				time->d -= 1;
286 			}
287 		} else if (dow == 6) {
288 			/* We ended up on Saturday, but there's still work to do, so move
289 			 * to Sunday and continue from there. */
290 			time->d += 1;
291 		} else if (dow + rem > 5) {
292 			/* We're on a weekday, but we're going past Friday, so skip right
293 			 * over the weekend. */
294 			time->d += 2;
295 		}
296 	} else {
297 		/* Completely mirror the forward direction. This also covers the 0
298 		 * case, since if we start on the weekend, we want to move forward as
299 		 * if we stopped there while going backwards. */
300 		if (rem == 0) {
301 			if (dow == 6) {
302 				time->d += 2;
303 			} else if (dow == 0) {
304 				time->d += 1;
305 			}
306 		} else if (dow == 0) {
307 			time->d -= 1;
308 		} else if (dow + rem < 1) {
309 			time->d -= 2;
310 		}
311 	}
312 
313 	time->d += rem;
314 }
315 
do_adjust_special(timelib_time * time)316 static void do_adjust_special(timelib_time* time)
317 {
318 	if (time->relative.have_special_relative) {
319 		switch (time->relative.special.type) {
320 			case TIMELIB_SPECIAL_WEEKDAY:
321 				do_adjust_special_weekday(time);
322 				break;
323 		}
324 	}
325 	timelib_do_normalize(time);
326 	memset(&(time->relative.special), 0, sizeof(time->relative.special));
327 }
328 
do_adjust_special_early(timelib_time * time)329 static void do_adjust_special_early(timelib_time* time)
330 {
331 	if (time->relative.have_special_relative) {
332 		switch (time->relative.special.type) {
333 			case TIMELIB_SPECIAL_DAY_OF_WEEK_IN_MONTH:
334 				time->d = 1;
335 				time->m += time->relative.m;
336 				time->relative.m = 0;
337 				break;
338 			case TIMELIB_SPECIAL_LAST_DAY_OF_WEEK_IN_MONTH:
339 				time->d = 1;
340 				time->m += time->relative.m + 1;
341 				time->relative.m = 0;
342 				break;
343 		}
344 	}
345 	switch (time->relative.first_last_day_of) {
346 		case TIMELIB_SPECIAL_FIRST_DAY_OF_MONTH: /* first */
347 			time->d = 1;
348 			break;
349 		case TIMELIB_SPECIAL_LAST_DAY_OF_MONTH: /* last */
350 			time->d = 0;
351 			time->m++;
352 			break;
353 	}
354 	timelib_do_normalize(time);
355 }
356 
do_adjust_timezone(timelib_time * tz,timelib_tzinfo * tzi)357 static void do_adjust_timezone(timelib_time *tz, timelib_tzinfo *tzi)
358 {
359 	switch (tz->zone_type) {
360 		case TIMELIB_ZONETYPE_OFFSET:
361 
362 			tz->is_localtime = 1;
363 			tz->sse += -tz->z;
364 			return;
365 
366 		case TIMELIB_ZONETYPE_ABBR: {
367 
368 			tz->is_localtime = 1;
369 			tz->sse += (-tz->z - tz->dst * SECS_PER_HOUR);
370 			return;
371 		}
372 
373 		case TIMELIB_ZONETYPE_ID:
374 			tzi = tz->tz_info;
375 			TIMELIB_BREAK_INTENTIONALLY_MISSING
376 
377 		default: {
378 			/* No timezone in struct, fallback to reference if possible */
379 			timelib_time_offset *current, *after;
380 			timelib_sll          adjustment;
381 			int                  in_transition;
382 			int32_t              actual_offset;
383 			timelib_sll          actual_transition_time;
384 
385 			if (!tzi) {
386 				return;
387 			}
388 
389 			current = timelib_get_time_zone_info(tz->sse, tzi);
390 			after = timelib_get_time_zone_info(tz->sse - current->offset, tzi);
391 			actual_offset = after->offset;
392 			actual_transition_time = after->transition_time;
393 			if (current->offset == after->offset && tz->have_zone) {
394 				/* Make sure we're not missing a DST change because we don't know the actual offset yet */
395 				if (current->offset >= 0 && tz->dst && !current->is_dst) {
396 						/* Timezone or its DST at or east of UTC, so the local time, interpreted as UTC, leaves DST (as defined in the actual timezone) before the actual local time */
397 						timelib_time_offset *earlier;
398 						earlier = timelib_get_time_zone_info(tz->sse - current->offset - 7200, tzi);
399 						if ((earlier->offset != after->offset) && (tz->sse - earlier->offset < after->transition_time)) {
400 								/* Looking behind a bit clarified the actual offset to use */
401 								actual_offset = earlier->offset;
402 								actual_transition_time = earlier->transition_time;
403 						}
404 						timelib_time_offset_dtor(earlier);
405 				} else if (current->offset <= 0 && current->is_dst && !tz->dst) {
406 						/* Timezone west of UTC, so the local time, interpreted as UTC, leaves DST (as defined in the actual timezone) after the actual local time */
407 						timelib_time_offset *later;
408 						later = timelib_get_time_zone_info(tz->sse - current->offset + 7200, tzi);
409 						if ((later->offset != after->offset) && (tz->sse - later->offset >= later->transition_time)) {
410 								/* Looking ahead a bit clarified the actual offset to use */
411 								actual_offset = later->offset;
412 								actual_transition_time = later->transition_time;
413 						}
414 						timelib_time_offset_dtor(later);
415 				}
416 			}
417 
418 			tz->is_localtime = 1;
419 
420 			in_transition = (
421 				((tz->sse - actual_offset) >= (actual_transition_time + (current->offset - actual_offset))) &&
422 				((tz->sse - actual_offset) < actual_transition_time)
423 			);
424 
425 			if ((current->offset != actual_offset) && !in_transition) {
426 				adjustment = -actual_offset;
427 			} else {
428 				adjustment = -current->offset;
429 			}
430 			timelib_time_offset_dtor(current);
431 			timelib_time_offset_dtor(after);
432 
433 			tz->sse += adjustment;
434 			timelib_set_timezone(tz, tzi);
435 			return;
436 		}
437 	}
438 	return;
439 }
440 
timelib_epoch_days_from_time(timelib_time * time)441 timelib_sll timelib_epoch_days_from_time(timelib_time *time)
442 {
443 	timelib_sll y = time->y; // Make copy, as we don't want to change the original one
444 	timelib_sll era, year_of_era, day_of_year, day_of_era;
445 
446 	y -= time->m <= 2;
447 	era = (y >= 0 ? y : y - 399) / YEARS_PER_ERA;
448 	year_of_era = y - era * YEARS_PER_ERA;                                                        // [0, 399]
449 	day_of_year = (153 * (time->m + (time->m > 2 ? -3 : 9)) + 2)/5 + time->d - 1;                 // [0, 365]
450 	day_of_era = year_of_era * DAYS_PER_YEAR + year_of_era / 4 - year_of_era / 100 + day_of_year; // [0, 146096]
451 
452 	return era * DAYS_PER_ERA + day_of_era - HINNANT_EPOCH_SHIFT;
453 }
454 
timelib_update_ts(timelib_time * time,timelib_tzinfo * tzi)455 void timelib_update_ts(timelib_time* time, timelib_tzinfo* tzi)
456 {
457 	do_adjust_special_early(time);
458 	do_adjust_relative(time);
459 	do_adjust_special(time);
460 
461 	time->sse =
462 		(timelib_epoch_days_from_time(time) * SECS_PER_DAY) +
463 		timelib_hms_to_seconds(time->h, time->i, time->s);
464 
465 	// This modifies time->sse, if needed
466 	do_adjust_timezone(time, tzi);
467 
468 	time->sse_uptodate = 1;
469 	time->have_relative = time->relative.have_weekday_relative = time->relative.have_special_relative = time->relative.first_last_day_of = 0;
470 }
471 
472 #if 0
473 int main(void)
474 {
475 	timelib_sll res;
476 	timelib_time time;
477 
478 	time = timelib_strtotime("10 Feb 2005 06:07:03 PM CET"); /* 1108055223 */
479 	printf ("%04d-%02d-%02d %02d:%02d:%02d.%-5d %+04d %1d",
480 		time.y, time.m, time.d, time.h, time.i, time.s, time.f, time.z, time.dst);
481 	if (time.have_relative) {
482 		printf ("%3dY %3dM %3dD / %3dH %3dM %3dS",
483 			time.relative.y, time.relative.m, time.relative.d, time.relative.h, time.relative.i, time.relative.s);
484 	}
485 	if (time.have_weekday_relative) {
486 		printf (" / %d", time.relative.weekday);
487 	}
488 	res = time2unixtime(&time);
489 	printf("%Ld\n", res);
490 
491 	return 0;
492 }
493 #endif
494