mktime.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /* Convert a `struct tm' to a time_t value.
  2. Copyright (C) 1993, 94, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Paul Eggert (eggert@twinsun.com).
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, write to the Free
  15. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 USA. */
  17. /* Define this to have a standalone program to test this implementation of
  18. mktime. */
  19. #include <features.h>
  20. /* Assume that leap seconds are not possible */
  21. #undef LEAP_SECONDS_POSSIBLE
  22. #include <sys/types.h> /* Some systems define `time_t' here. */
  23. #include <time.h>
  24. #include <limits.h>
  25. #if 0
  26. #ifndef CHAR_BIT
  27. # define CHAR_BIT 8
  28. #endif
  29. /* The extra casts work around common compiler bugs. */
  30. #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
  31. /* The outer cast is needed to work around a bug in Cray C 5.0.3.0.
  32. It is necessary at least when t == time_t. */
  33. #define TYPE_MINIMUM(t) ((t) (TYPE_SIGNED (t) \
  34. ? ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1) : (t) 0))
  35. #define TYPE_MAXIMUM(t) ((t) (~ (t) 0 - TYPE_MINIMUM (t)))
  36. #ifndef INT_MIN
  37. # define INT_MIN TYPE_MINIMUM (int)
  38. #endif
  39. #ifndef INT_MAX
  40. # define INT_MAX TYPE_MAXIMUM (int)
  41. #endif
  42. #ifndef TIME_T_MIN
  43. # define TIME_T_MIN TYPE_MINIMUM (time_t)
  44. #endif
  45. #ifndef TIME_T_MAX
  46. # define TIME_T_MAX TYPE_MAXIMUM (time_t)
  47. #endif
  48. #define TM_YEAR_BASE 1900
  49. #define EPOCH_YEAR 1970
  50. /* How many days come before each month (0-12). */
  51. extern const unsigned short int __mon_yday[2][13];
  52. /* Yield the difference between (YEAR-YDAY HOUR:MIN:SEC) and (*TP),
  53. measured in seconds, ignoring leap seconds.
  54. YEAR uses the same numbering as TM->tm_year.
  55. All values are in range, except possibly YEAR.
  56. If TP is null, return a nonzero value.
  57. If overflow occurs, yield the low order bits of the correct answer. */
  58. static time_t
  59. __ydhms_tm_diff (int year, int yday, int hour, int min, int sec,
  60. const struct tm *tp)
  61. {
  62. if (!tp)
  63. return 1;
  64. else
  65. {
  66. /* Compute intervening leap days correctly even if year is negative.
  67. Take care to avoid int overflow. time_t overflow is OK, since
  68. only the low order bits of the correct time_t answer are needed.
  69. Don't convert to time_t until after all divisions are done, since
  70. time_t might be unsigned. */
  71. int a4 = (year >> 2) + (TM_YEAR_BASE >> 2) - ! (year & 3);
  72. int b4 = (tp->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (tp->tm_year & 3);
  73. int a100 = a4 / 25 - (a4 % 25 < 0);
  74. int b100 = b4 / 25 - (b4 % 25 < 0);
  75. int a400 = a100 >> 2;
  76. int b400 = b100 >> 2;
  77. int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
  78. time_t years = year - (time_t) tp->tm_year;
  79. time_t days = (365 * years + intervening_leap_days
  80. + (yday - tp->tm_yday));
  81. return (60 * (60 * (24 * days + (hour - tp->tm_hour))
  82. + (min - tp->tm_min))
  83. + (sec - tp->tm_sec));
  84. }
  85. }
  86. /* Use CONVERT to convert *T to a broken down time in *TP.
  87. If *T is out of range for conversion, adjust it so that
  88. it is the nearest in-range value and then convert that. */
  89. static struct tm *
  90. __ranged_convert (struct tm *(*convert) (const time_t *, struct tm *),
  91. time_t *t, struct tm *tp)
  92. {
  93. struct tm *r;
  94. if (! (r = (*convert) (t, tp)) && *t)
  95. {
  96. time_t bad = *t;
  97. time_t ok = 0;
  98. struct tm tm;
  99. /* BAD is a known unconvertible time_t, and OK is a known good one.
  100. Use binary search to narrow the range between BAD and OK until
  101. they differ by 1. */
  102. while (bad != ok + (bad < 0 ? -1 : 1))
  103. {
  104. time_t mid = *t = (bad < 0
  105. ? bad + ((ok - bad) >> 1)
  106. : ok + ((bad - ok) >> 1));
  107. if ((r = (*convert) (t, tp)))
  108. {
  109. tm = *r;
  110. ok = mid;
  111. }
  112. else
  113. bad = mid;
  114. }
  115. if (!r && ok)
  116. {
  117. /* The last conversion attempt failed;
  118. revert to the most recent successful attempt. */
  119. *t = ok;
  120. *tp = tm;
  121. r = tp;
  122. }
  123. }
  124. return r;
  125. }
  126. /* Convert *TP to a time_t value, inverting
  127. the monotonic and mostly-unit-linear conversion function CONVERT.
  128. Use *OFFSET to keep track of a guess at the offset of the result,
  129. compared to what the result would be for UTC without leap seconds.
  130. If *OFFSET's guess is correct, only one CONVERT call is needed. */
  131. time_t __mktime_internal (struct tm *tp,
  132. struct tm *(*convert) (const time_t *, struct tm *), time_t *offset)
  133. {
  134. time_t t, dt, t0, t1, t2;
  135. struct tm tm;
  136. /* The maximum number of probes (calls to CONVERT) should be enough
  137. to handle any combinations of time zone rule changes, solar time,
  138. leap seconds, and oscillations around a spring-forward gap.
  139. POSIX.1 prohibits leap seconds, but some hosts have them anyway. */
  140. int remaining_probes = 6;
  141. /* Time requested. Copy it in case CONVERT modifies *TP; this can
  142. occur if TP is localtime's returned value and CONVERT is localtime. */
  143. int sec = tp->tm_sec;
  144. int min = tp->tm_min;
  145. int hour = tp->tm_hour;
  146. int mday = tp->tm_mday;
  147. int mon = tp->tm_mon;
  148. int year_requested = tp->tm_year;
  149. int isdst = tp->tm_isdst;
  150. /* Ensure that mon is in range, and set year accordingly. */
  151. int mon_remainder = mon % 12;
  152. int negative_mon_remainder = mon_remainder < 0;
  153. int mon_years = mon / 12 - negative_mon_remainder;
  154. int year = year_requested + mon_years;
  155. /* The other values need not be in range:
  156. the remaining code handles minor overflows correctly,
  157. assuming int and time_t arithmetic wraps around.
  158. Major overflows are caught at the end. */
  159. /* Calculate day of year from year, month, and day of month.
  160. The result need not be in range. */
  161. int yday = ((__mon_yday[__isleap (year + TM_YEAR_BASE)]
  162. [mon_remainder + 12 * negative_mon_remainder])
  163. + mday - 1);
  164. int sec_requested = sec;
  165. #if LEAP_SECONDS_POSSIBLE
  166. /* Handle out-of-range seconds specially,
  167. since __ydhms_tm_diff assumes every minute has 60 seconds. */
  168. if (sec < 0)
  169. sec = 0;
  170. if (59 < sec)
  171. sec = 59;
  172. #endif
  173. /* Invert CONVERT by probing. First assume the same offset as last time.
  174. Then repeatedly use the error to improve the guess. */
  175. tm.tm_year = EPOCH_YEAR - TM_YEAR_BASE;
  176. tm.tm_yday = tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
  177. t0 = __ydhms_tm_diff (year, yday, hour, min, sec, &tm);
  178. for (t = t1 = t2 = t0 + *offset;
  179. (dt = __ydhms_tm_diff (year, yday, hour, min, sec,
  180. __ranged_convert (convert, &t, &tm)));
  181. t1 = t2, t2 = t, t += dt)
  182. if (t == t1 && t != t2
  183. && (isdst < 0 || tm.tm_isdst < 0
  184. || (isdst != 0) != (tm.tm_isdst != 0)))
  185. /* We can't possibly find a match, as we are oscillating
  186. between two values. The requested time probably falls
  187. within a spring-forward gap of size DT. Follow the common
  188. practice in this case, which is to return a time that is DT
  189. away from the requested time, preferring a time whose
  190. tm_isdst differs from the requested value. In practice,
  191. this is more useful than returning -1. */
  192. break;
  193. else if (--remaining_probes == 0)
  194. return -1;
  195. /* If we have a match, check whether tm.tm_isdst has the requested
  196. value, if any. */
  197. if (dt == 0 && isdst != tm.tm_isdst && 0 <= isdst && 0 <= tm.tm_isdst)
  198. {
  199. /* tm.tm_isdst has the wrong value. Look for a neighboring
  200. time with the right value, and use its UTC offset.
  201. Heuristic: probe the previous three calendar quarters (approximately),
  202. looking for the desired isdst. This isn't perfect,
  203. but it's good enough in practice. */
  204. int quarter = 7889238; /* seconds per average 1/4 Gregorian year */
  205. int i;
  206. /* If we're too close to the time_t limit, look in future quarters. */
  207. if (t < TIME_T_MIN + 3 * quarter)
  208. quarter = -quarter;
  209. for (i = 1; i <= 3; i++)
  210. {
  211. time_t ot = t - i * quarter;
  212. struct tm otm;
  213. __ranged_convert (convert, &ot, &otm);
  214. if (otm.tm_isdst == isdst)
  215. {
  216. /* We found the desired tm_isdst.
  217. Extrapolate back to the desired time. */
  218. t = ot + __ydhms_tm_diff (year, yday, hour, min, sec, &otm);
  219. __ranged_convert (convert, &t, &tm);
  220. break;
  221. }
  222. }
  223. }
  224. *offset = t - t0;
  225. #if LEAP_SECONDS_POSSIBLE
  226. if (sec_requested != tm.tm_sec)
  227. {
  228. /* Adjust time to reflect the tm_sec requested, not the normalized value.
  229. Also, repair any damage from a false match due to a leap second. */
  230. t += sec_requested - sec + (sec == 0 && tm.tm_sec == 60);
  231. if (! (*convert) (&t, &tm))
  232. return -1;
  233. }
  234. #endif
  235. if (TIME_T_MAX / INT_MAX / 366 / 24 / 60 / 60 < 3)
  236. {
  237. /* time_t isn't large enough to rule out overflows in __ydhms_tm_diff,
  238. so check for major overflows. A gross check suffices,
  239. since if t has overflowed, it is off by a multiple of
  240. TIME_T_MAX - TIME_T_MIN + 1. So ignore any component of
  241. the difference that is bounded by a small value. */
  242. double dyear = (double) year_requested + mon_years - tm.tm_year;
  243. double dday = 366 * dyear + mday;
  244. double dsec = 60 * (60 * (24 * dday + hour) + min) + sec_requested;
  245. /* On Irix4.0.5 cc, dividing TIME_T_MIN by 3 does not produce
  246. correct results, ie., it erroneously gives a positive value
  247. of 715827882. Setting a variable first then doing math on it
  248. seems to work. (ghazi@caip.rutgers.edu) */
  249. const time_t time_t_max = TIME_T_MAX;
  250. const time_t time_t_min = TIME_T_MIN;
  251. if (time_t_max / 3 - time_t_min / 3 < (dsec < 0 ? - dsec : dsec))
  252. return -1;
  253. }
  254. *tp = tm;
  255. return t;
  256. }
  257. /* Convert *TP to a time_t value. */
  258. time_t mktime (struct tm *tp)
  259. {
  260. static time_t localtime_offset;
  261. /* POSIX.1 8.1.1 requires that whenever mktime() is called, the
  262. time zone names contained in the external variable `tzname' shall
  263. be set as if the tzset() function had been called. */
  264. tzset ();
  265. return __mktime_internal (tp, localtime_r, &localtime_offset);
  266. }
  267. #else
  268. /* Convert *TP to a time_t value. */
  269. time_t mktime (struct tm *tp)
  270. {
  271. time_t m_secs=tp->tm_min*60;
  272. time_t h_secs=tp->tm_hour*3600;
  273. time_t d_secs=tp->tm_yday*86400;
  274. time_t y_secs=(tp->tm_year-70)*31536000;
  275. time_t l_secs1=((tp->tm_year-69)/4)*86400;
  276. time_t l_secs2=((tp->tm_year-1)/100)*86400;
  277. time_t l_secs3=((tp->tm_year+299)/400)*86400;
  278. return m_secs+h_secs+d_secs+y_secs+l_secs1-l_secs2+l_secs3+tp->tm_gmtoff;
  279. }
  280. #endif