1 /* Convert a 'struct tm' to a time_t value.
2 Copyright (C) 1993-2018 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Paul Eggert <eggert@twinsun.com>.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
20 /* Define this to 1 to have a standalone program to test this implementation of
23 # define DEBUG_MKTIME 0
26 /* The following macros influence what gets defined when this file is compiled:
28 Macro/expression Which gnulib module This compilation unit
31 _LIBC (glibc proper) mktime
33 NEED_MKTIME_WORKING mktime rpl_mktime
34 || NEED_MKTIME_WINDOWS
36 NEED_MKTIME_INTERNAL mktime-internal mktime_internal
38 DEBUG_MKTIME (defined manually) my_mktime, main
41 #if !defined _LIBC && !DEBUG_MKTIME
42 # include <libc-config.h>
45 /* Assume that leap seconds are possible, unless told otherwise.
46 If the host has a 'zic' command with a '-L leapsecondfilename' option,
47 then it supports leap seconds; otherwise it probably doesn't. */
48 #ifndef LEAP_SECONDS_POSSIBLE
49 # define LEAP_SECONDS_POSSIBLE 1
65 /* Make it work even if the system's libc has its own mktime routine. */
67 # define mktime my_mktime
68 #endif /* DEBUG_MKTIME */
70 #ifndef NEED_MKTIME_INTERNAL
71 # define NEED_MKTIME_INTERNAL 0
73 #ifndef NEED_MKTIME_WINDOWS
74 # define NEED_MKTIME_WINDOWS 0
76 #ifndef NEED_MKTIME_WORKING
77 # define NEED_MKTIME_WORKING DEBUG_MKTIME
80 #include "mktime-internal.h"
82 #if !defined _LIBC && (NEED_MKTIME_WORKING || NEED_MKTIME_WINDOWS)
86 # if NEED_MKTIME_WINDOWS
87 /* Rectify the value of the environment variable TZ.
88 There are four possible kinds of such values:
89 - Traditional US time zone names, e.g. "PST8PDT". Syntax: see
90 <https://msdn.microsoft.com/en-us/library/90s5c885.aspx>
91 - Time zone names based on geography, that contain one or more
92 slashes, e.g. "Europe/Moscow".
93 - Time zone names based on geography, without slashes, e.g.
95 - Time zone names that contain explicit DST rules. Syntax: see
96 <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03>
97 The Microsoft CRT understands only the first kind. It produces incorrect
98 results if the value of TZ is of the other kinds.
99 But in a Cygwin environment, /etc/profile.d/tzset.sh sets TZ to a value
100 of the second kind for most geographies, or of the first kind in a few
101 other geographies. If it is of the second kind, neutralize it. For the
102 Microsoft CRT, an absent or empty TZ means the time zone that the user
103 has set in the Windows Control Panel.
104 If the value of TZ is of the third or fourth kind -- Cygwin programs
105 understand these syntaxes as well --, it does not matter whether we
106 neutralize it or not, since these values occur only when a Cygwin user
107 has set TZ explicitly; this case is 1. rare and 2. under the user's
109 const char *tz
= getenv ("TZ");
110 if (tz
!= NULL
&& strchr (tz
, '/') != NULL
)
117 # define __tzset() my_tzset ()
120 #if defined _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_INTERNAL
122 /* A signed type that can represent an integer number of years
123 multiplied by four times the number of seconds in a year. It is
124 needed when converting a tm_year value times the number of seconds
125 in a year. The factor of four comes because these products need
126 to be subtracted from each other, and sometimes with an offset
127 added to them, and then with another timestamp added, without
128 worrying about overflow.
130 Much of the code uses long_int to represent time_t values, to
131 lessen the hassle of dealing with platforms where time_t is
132 unsigned, and because long_int should suffice to represent all
133 time_t values that mktime can generate even on platforms where
134 time_t is excessively wide. */
136 #if INT_MAX <= LONG_MAX / 4 / 366 / 24 / 60 / 60
137 typedef long int long_int
;
139 typedef long long int long_int
;
141 verify (INT_MAX
<= TYPE_MAXIMUM (long_int
) / 4 / 366 / 24 / 60 / 60);
143 /* Shift A right by B bits portably, by dividing A by 2**B and
144 truncating towards minus infinity. B should be in the range 0 <= B
145 <= LONG_INT_BITS - 2, where LONG_INT_BITS is the number of useful
146 bits in a long_int. LONG_INT_BITS is at least 32.
148 ISO C99 says that A >> B is implementation-defined if A < 0. Some
149 implementations (e.g., UNICOS 9.0 on a Cray Y-MP EL) don't shift
150 right in the usual way when A < 0, so SHR falls back on division if
151 ordinary A >> B doesn't seem to be the usual signed shift. */
154 shr (long_int a
, int b
)
157 return (-one
>> 1 == -1
159 : a
/ (one
<< b
) - (a
% (one
<< b
) < 0));
162 /* Bounds for the intersection of time_t and long_int. */
164 static long_int
const mktime_min
165 = ((TYPE_SIGNED (time_t) && TYPE_MINIMUM (time_t) < TYPE_MINIMUM (long_int
))
166 ? TYPE_MINIMUM (long_int
) : TYPE_MINIMUM (time_t));
167 static long_int
const mktime_max
168 = (TYPE_MAXIMUM (long_int
) < TYPE_MAXIMUM (time_t)
169 ? TYPE_MAXIMUM (long_int
) : TYPE_MAXIMUM (time_t));
171 verify (TYPE_IS_INTEGER (time_t));
173 #define EPOCH_YEAR 1970
174 #define TM_YEAR_BASE 1900
175 verify (TM_YEAR_BASE
% 100 == 0);
177 /* Is YEAR + TM_YEAR_BASE a leap year? */
179 leapyear (long_int year
)
181 /* Don't add YEAR to TM_YEAR_BASE, as that might overflow.
182 Also, work even if YEAR is negative. */
186 || ((year
/ 100) & 3) == (- (TM_YEAR_BASE
/ 100) & 3)));
189 /* How many days come before each month (0-12). */
193 const unsigned short int __mon_yday
[2][13] =
196 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
198 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
202 /* Do the values A and B differ according to the rules for tm_isdst?
203 A and B differ if one is zero and the other positive. */
205 isdst_differ (int a
, int b
)
207 return (!a
!= !b
) && (0 <= a
) && (0 <= b
);
210 /* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
211 (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds, assuming that the clocks
212 were not adjusted between the timestamps.
214 The YEAR values uses the same numbering as TP->tm_year. Values
215 need not be in the usual range. However, YEAR1 - YEAR0 must not
216 overflow even when multiplied by three times the number of seconds
217 in a year, and likewise for YDAY1 - YDAY0 and three times the
218 number of seconds in a day. */
221 ydhms_diff (long_int year1
, long_int yday1
, int hour1
, int min1
, int sec1
,
222 int year0
, int yday0
, int hour0
, int min0
, int sec0
)
224 verify (-1 / 2 == 0);
226 /* Compute intervening leap days correctly even if year is negative.
227 Take care to avoid integer overflow here. */
228 int a4
= shr (year1
, 2) + shr (TM_YEAR_BASE
, 2) - ! (year1
& 3);
229 int b4
= shr (year0
, 2) + shr (TM_YEAR_BASE
, 2) - ! (year0
& 3);
230 int a100
= a4
/ 25 - (a4
% 25 < 0);
231 int b100
= b4
/ 25 - (b4
% 25 < 0);
232 int a400
= shr (a100
, 2);
233 int b400
= shr (b100
, 2);
234 int intervening_leap_days
= (a4
- b4
) - (a100
- b100
) + (a400
- b400
);
236 /* Compute the desired time without overflowing. */
237 long_int years
= year1
- year0
;
238 long_int days
= 365 * years
+ yday1
- yday0
+ intervening_leap_days
;
239 long_int hours
= 24 * days
+ hour1
- hour0
;
240 long_int minutes
= 60 * hours
+ min1
- min0
;
241 long_int seconds
= 60 * minutes
+ sec1
- sec0
;
245 /* Return the average of A and B, even if A + B would overflow.
246 Round toward positive infinity. */
248 long_int_avg (long_int a
, long_int b
)
250 return shr (a
, 1) + shr (b
, 1) + ((a
| b
) & 1);
253 /* Return a time_t value corresponding to (YEAR-YDAY HOUR:MIN:SEC),
254 assuming that T corresponds to *TP and that no clock adjustments
255 occurred between *TP and the desired time.
256 Although T and the returned value are of type long_int,
257 they represent time_t values and must be in time_t range.
258 If TP is null, return a value not equal to T; this avoids false matches.
259 YEAR and YDAY must not be so large that multiplying them by three times the
260 number of seconds in a year (or day, respectively) would overflow long_int.
261 If TP is non-null and the returned value would be out of range, set
262 errno to EOVERFLOW and yield a minimal or maximal in-range value
263 that is not equal to T. */
265 guess_time_tm (long_int year
, long_int yday
, int hour
, int min
, int sec
,
266 long_int t
, const struct tm
*tp
)
271 long_int d
= ydhms_diff (year
, yday
, hour
, min
, sec
,
272 tp
->tm_year
, tp
->tm_yday
,
273 tp
->tm_hour
, tp
->tm_min
, tp
->tm_sec
);
274 if (! INT_ADD_WRAPV (t
, d
, &result
))
276 __set_errno (EOVERFLOW
);
279 /* An error occurred, probably overflow. Return the nearest result
280 that is actually in range, except don't report a zero difference
281 if the actual difference is nonzero, as that would cause a false
282 match; and don't oscillate between two values, as that would
283 confuse the spring-forward gap detector. */
284 return (t
< long_int_avg (mktime_min
, mktime_max
)
285 ? (t
<= mktime_min
+ 1 ? t
+ 1 : mktime_min
)
286 : (mktime_max
- 1 <= t
? t
- 1 : mktime_max
));
289 /* Use CONVERT to convert T to a struct tm value in *TM. T must be in
290 range for time_t. Return TM if successful, NULL if T is out of
291 range for CONVERT. */
293 convert_time (struct tm
*(*convert
) (const time_t *, struct tm
*),
294 long_int t
, struct tm
*tm
)
297 return convert (&x
, tm
);
300 /* Use CONVERT to convert *T to a broken down time in *TP.
301 If *T is out of range for conversion, adjust it so that
302 it is the nearest in-range value and then convert that.
303 A value is in range if it fits in both time_t and long_int. */
305 ranged_convert (struct tm
*(*convert
) (const time_t *, struct tm
*),
306 long_int
*t
, struct tm
*tp
)
311 else if (mktime_max
< *t
)
313 r
= convert_time (convert
, *t
, tp
);
320 /* BAD is a known unconvertible value, and OK is a known good one.
321 Use binary search to narrow the range between BAD and OK until
325 long_int mid
= long_int_avg (ok
, bad
);
326 if (mid
!= ok
&& mid
!= bad
)
328 r
= convert_time (convert
, mid
, tp
);
337 /* The last conversion attempt failed;
338 revert to the most recent successful attempt. */
339 r
= convert_time (convert
, ok
, tp
);
347 /* Convert *TP to a time_t value, inverting
348 the monotonic and mostly-unit-linear conversion function CONVERT.
349 Use *OFFSET to keep track of a guess at the offset of the result,
350 compared to what the result would be for UTC without leap seconds.
351 If *OFFSET's guess is correct, only one CONVERT call is needed.
352 If successful, set *TP to the canonicalized struct tm;
353 otherwise leave *TP alone, return ((time_t) -1) and set errno.
354 This function is external because it is used also by timegm.c. */
356 __mktime_internal (struct tm
*tp
,
357 struct tm
*(*convert
) (const time_t *, struct tm
*),
358 mktime_offset_t
*offset
)
360 long_int t
, gt
, t0
, t1
, t2
;
363 /* The maximum number of probes (calls to CONVERT) should be enough
364 to handle any combinations of time zone rule changes, solar time,
365 leap seconds, and oscillations around a spring-forward gap.
366 POSIX.1 prohibits leap seconds, but some hosts have them anyway. */
367 int remaining_probes
= 6;
369 /* Time requested. Copy it in case CONVERT modifies *TP; this can
370 occur if TP is localtime's returned value and CONVERT is localtime. */
371 int sec
= tp
->tm_sec
;
372 int min
= tp
->tm_min
;
373 int hour
= tp
->tm_hour
;
374 int mday
= tp
->tm_mday
;
375 int mon
= tp
->tm_mon
;
376 int year_requested
= tp
->tm_year
;
377 int isdst
= tp
->tm_isdst
;
379 /* 1 if the previous probe was DST. */
382 /* Ensure that mon is in range, and set year accordingly. */
383 int mon_remainder
= mon
% 12;
384 int negative_mon_remainder
= mon_remainder
< 0;
385 int mon_years
= mon
/ 12 - negative_mon_remainder
;
386 long_int lyear_requested
= year_requested
;
387 long_int year
= lyear_requested
+ mon_years
;
389 /* The other values need not be in range:
390 the remaining code handles overflows correctly. */
392 /* Calculate day of year from year, month, and day of month.
393 The result need not be in range. */
394 int mon_yday
= ((__mon_yday
[leapyear (year
)]
395 [mon_remainder
+ 12 * negative_mon_remainder
])
397 long_int lmday
= mday
;
398 long_int yday
= mon_yday
+ lmday
;
400 mktime_offset_t off
= *offset
;
401 int negative_offset_guess
;
403 int sec_requested
= sec
;
405 if (LEAP_SECONDS_POSSIBLE
)
407 /* Handle out-of-range seconds specially,
408 since ydhms_diff assumes every minute has 60 seconds. */
415 /* Invert CONVERT by probing. First assume the same offset as last
418 INT_SUBTRACT_WRAPV (0, off
, &negative_offset_guess
);
419 t0
= ydhms_diff (year
, yday
, hour
, min
, sec
,
420 EPOCH_YEAR
- TM_YEAR_BASE
, 0, 0, 0, negative_offset_guess
);
422 /* Repeatedly use the error to improve the guess. */
424 for (t
= t1
= t2
= t0
, dst2
= 0;
425 (gt
= guess_time_tm (year
, yday
, hour
, min
, sec
, t
,
426 ranged_convert (convert
, &t
, &tm
)),
428 t1
= t2
, t2
= t
, t
= gt
, dst2
= tm
.tm_isdst
!= 0)
429 if (t
== t1
&& t
!= t2
432 ? dst2
<= (tm
.tm_isdst
!= 0)
433 : (isdst
!= 0) != (tm
.tm_isdst
!= 0))))
434 /* We can't possibly find a match, as we are oscillating
435 between two values. The requested time probably falls
436 within a spring-forward gap of size GT - T. Follow the common
437 practice in this case, which is to return a time that is GT - T
438 away from the requested time, preferring a time whose
439 tm_isdst differs from the requested value. (If no tm_isdst
440 was requested and only one of the two values has a nonzero
441 tm_isdst, prefer that value.) In practice, this is more
442 useful than returning -1. */
444 else if (--remaining_probes
== 0)
446 __set_errno (EOVERFLOW
);
450 /* We have a match. Check whether tm.tm_isdst has the requested
452 if (isdst_differ (isdst
, tm
.tm_isdst
))
454 /* tm.tm_isdst has the wrong value. Look for a neighboring
455 time with the right value, and use its UTC offset.
457 Heuristic: probe the adjacent timestamps in both directions,
458 looking for the desired isdst. This should work for all real
459 time zone histories in the tz database. */
461 /* Distance between probes when looking for a DST boundary. In
462 tzdata2003a, the shortest period of DST is 601200 seconds
463 (e.g., America/Recife starting 2000-10-08 01:00), and the
464 shortest period of non-DST surrounded by DST is 694800
465 seconds (Africa/Tunis starting 1943-04-17 01:00). Use the
466 minimum of these two values, so we don't miss these short
467 periods when probing. */
470 /* The longest period of DST in tzdata2003a is 536454000 seconds
471 (e.g., America/Jujuy starting 1946-10-01 01:00). The longest
472 period of non-DST is much longer, but it makes no real sense
473 to search for more than a year of non-DST, so use the DST
475 int duration_max
= 536454000;
477 /* Search in both directions, so the maximum distance is half
478 the duration; add the stride to avoid off-by-1 problems. */
479 int delta_bound
= duration_max
/ 2 + stride
;
481 int delta
, direction
;
483 for (delta
= stride
; delta
< delta_bound
; delta
+= stride
)
484 for (direction
= -1; direction
<= 1; direction
+= 2)
487 if (! INT_ADD_WRAPV (t
, delta
* direction
, &ot
))
490 ranged_convert (convert
, &ot
, &otm
);
491 if (! isdst_differ (isdst
, otm
.tm_isdst
))
493 /* We found the desired tm_isdst.
494 Extrapolate back to the desired time. */
495 t
= guess_time_tm (year
, yday
, hour
, min
, sec
, ot
, &otm
);
496 ranged_convert (convert
, &t
, &tm
);
504 /* Set *OFFSET to the low-order bits of T - T0 - NEGATIVE_OFFSET_GUESS.
505 This is just a heuristic to speed up the next mktime call, and
506 correctness is unaffected if integer overflow occurs here. */
507 INT_SUBTRACT_WRAPV (t
, t0
, offset
);
508 INT_SUBTRACT_WRAPV (*offset
, negative_offset_guess
, offset
);
510 if (LEAP_SECONDS_POSSIBLE
&& sec_requested
!= tm
.tm_sec
)
512 /* Adjust time to reflect the tm_sec requested, not the normalized value.
513 Also, repair any damage from a false match due to a leap second. */
514 long_int sec_adjustment
= sec
== 0 && tm
.tm_sec
== 60;
515 sec_adjustment
-= sec
;
516 sec_adjustment
+= sec_requested
;
517 if (INT_ADD_WRAPV (t
, sec_adjustment
, &t
)
518 || ! (mktime_min
<= t
&& t
<= mktime_max
))
520 __set_errno (EOVERFLOW
);
523 if (! convert_time (convert
, t
, &tm
))
531 #endif /* _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_INTERNAL */
533 #if defined _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_WINDOWS
535 /* Convert *TP to a time_t value. */
537 mktime (struct tm
*tp
)
539 /* POSIX.1 8.1.1 requires that whenever mktime() is called, the
540 time zone names contained in the external variable 'tzname' shall
541 be set as if the tzset() function had been called. */
544 # if defined _LIBC || NEED_MKTIME_WORKING
545 static mktime_offset_t localtime_offset
;
546 return __mktime_internal (tp
, __localtime_r
, &localtime_offset
);
552 #endif /* _LIBC || NEED_MKTIME_WORKING || NEED_MKTIME_WINDOWS */
555 weak_alias (mktime
, timelocal
)
559 libc_hidden_def (mktime
)
560 libc_hidden_weak (timelocal
)
566 not_equal_tm (const struct tm
*a
, const struct tm
*b
)
568 return ((a
->tm_sec
^ b
->tm_sec
)
569 | (a
->tm_min
^ b
->tm_min
)
570 | (a
->tm_hour
^ b
->tm_hour
)
571 | (a
->tm_mday
^ b
->tm_mday
)
572 | (a
->tm_mon
^ b
->tm_mon
)
573 | (a
->tm_year
^ b
->tm_year
)
574 | (a
->tm_yday
^ b
->tm_yday
)
575 | isdst_differ (a
->tm_isdst
, b
->tm_isdst
));
579 print_tm (const struct tm
*tp
)
582 printf ("%04d-%02d-%02d %02d:%02d:%02d yday %03d wday %d isdst %d",
583 tp
->tm_year
+ TM_YEAR_BASE
, tp
->tm_mon
+ 1, tp
->tm_mday
,
584 tp
->tm_hour
, tp
->tm_min
, tp
->tm_sec
,
585 tp
->tm_yday
, tp
->tm_wday
, tp
->tm_isdst
);
591 check_result (time_t tk
, struct tm tmk
, time_t tl
, const struct tm
*lt
)
593 if (tk
!= tl
|| !lt
|| not_equal_tm (&tmk
, lt
))
597 printf (")\nyields (");
599 printf (") == %ld, should be %ld\n", (long int) tk
, (long int) tl
);
607 main (int argc
, char **argv
)
610 struct tm tm
, tmk
, tml
;
615 /* Sanity check, plus call tzset. */
617 if (! localtime (&tl
))
619 printf ("localtime (0) fails\n");
623 if ((argc
== 3 || argc
== 4)
624 && (sscanf (argv
[1], "%d-%d-%d%c",
625 &tm
.tm_year
, &tm
.tm_mon
, &tm
.tm_mday
, &trailer
)
627 && (sscanf (argv
[2], "%d:%d:%d%c",
628 &tm
.tm_hour
, &tm
.tm_min
, &tm
.tm_sec
, &trailer
)
631 tm
.tm_year
-= TM_YEAR_BASE
;
633 tm
.tm_isdst
= argc
== 3 ? -1 : atoi (argv
[3]);
636 lt
= localtime_r (&tl
, &tml
);
637 printf ("mktime returns %ld == ", (long int) tl
);
640 status
= check_result (tl
, tmk
, tl
, lt
);
642 else if (argc
== 4 || (argc
== 5 && strcmp (argv
[4], "-") == 0))
644 time_t from
= atol (argv
[1]);
645 time_t by
= atol (argv
[2]);
646 time_t to
= atol (argv
[3]);
649 for (tl
= from
; by
< 0 ? to
<= tl
: tl
<= to
; tl
= tl1
)
651 lt
= localtime_r (&tl
, &tml
);
656 status
|= check_result (tk
, tmk
, tl
, &tml
);
660 printf ("localtime_r (%ld) yields 0\n", (long int) tl
);
664 if ((tl1
< tl
) != (by
< 0))
668 for (tl
= from
; by
< 0 ? to
<= tl
: tl
<= to
; tl
= tl1
)
670 /* Null benchmark. */
671 lt
= localtime_r (&tl
, &tml
);
676 status
|= check_result (tk
, tmk
, tl
, &tml
);
680 printf ("localtime_r (%ld) yields 0\n", (long int) tl
);
684 if ((tl1
< tl
) != (by
< 0))
690 \t%s YYYY-MM-DD HH:MM:SS [ISDST] # Test given time.\n\
691 \t%s FROM BY TO # Test values FROM, FROM+BY, ..., TO.\n\
692 \t%s FROM BY TO - # Do not test those values (for benchmark).\n",
693 argv
[0], argv
[0], argv
[0]);
698 #endif /* DEBUG_MKTIME */
702 compile-command: "gcc -DDEBUG_MKTIME -I. -Wall -W -O2 -g mktime.c -o mktime"