2 * @brief Portable implementation of timegm().
4 /* Copyright (c) 2013,2024 Olly Betts
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
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
32 safe_mktime(struct tm
* tm
)
34 time_t r
= mktime(tm
);
35 if (r
== time_t(-1) && tm
->tm_year
< 70 &&
36 (sizeof(time_t) > 4 || tm
->tm_year
>= 1)) {
37 /* Microsoft's mktime() treats years before 1970 as an error, unlike
38 * most other implementations.
40 * We workaround this to support older years by calling mktime() for a
41 * date offset such that it's after 1970 (but before 3000 which is the
42 * highest year Microsoft's mktime() handles, and also before 2038 for
43 * 32-bit time_t), and such that the leap year pattern matches. For
44 * 32-bit time_t we just need to add a multiple of 4, but for 64-bit
45 * time_t we need to add a multiple of 400.
47 * We require the year to be >= 1901 for 32-bit time_t since the
48 * oldest representable date in signed 32-bit time_t is in 1901
49 * so there's no point retrying anything older:
51 * Fri 13 Dec 1901 20:45:52 UTC
53 * For larger time_t we support any tm_year value which fits in an int.
54 * This is somewhat dubious before the adoption of the Gregorian
55 * calendar but it matches what most mktime() implementations seem to
59 int y_offset
= sizeof(time_t) > 4 ?
60 ((-1 - y
) / 400 + 1) * 400 :
62 tm
->tm_year
= y
+ y_offset
;
65 if (r
!= time_t(-1)) {
66 // The two magic numbers are the average number of seconds in a
67 // year for a 400 year cycle and for a 4 year cycle (one which
68 // includes a leap year).
69 r
-= y_offset
* time_t(sizeof(time_t) > 4 ? 31556952 : 31557600);
80 static bool set_tz
= false;
86 return safe_mktime(tm
);