Generic sys/param.h fixes for missing SYMLOOP_MAX or NGROUPS_MAX.
[glibc.git] / time / offtime.c
blob56c49f02016ff5320f6dbfe2163eab775e44ed90
1 /* Copyright (C) 1991, 1993, 1997, 1998, 2002 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 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.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
18 #include <errno.h>
19 #include <time.h>
21 #define SECS_PER_HOUR (60 * 60)
22 #define SECS_PER_DAY (SECS_PER_HOUR * 24)
24 /* Compute the `struct tm' representation of *T,
25 offset OFFSET seconds east of UTC,
26 and store year, yday, mon, mday, wday, hour, min, sec into *TP.
27 Return nonzero if successful. */
28 int
29 __offtime (t, offset, tp)
30 const time_t *t;
31 long int offset;
32 struct tm *tp;
34 time_t days, rem, y;
35 const unsigned short int *ip;
37 days = *t / SECS_PER_DAY;
38 rem = *t % SECS_PER_DAY;
39 rem += offset;
40 while (rem < 0)
42 rem += SECS_PER_DAY;
43 --days;
45 while (rem >= SECS_PER_DAY)
47 rem -= SECS_PER_DAY;
48 ++days;
50 tp->tm_hour = rem / SECS_PER_HOUR;
51 rem %= SECS_PER_HOUR;
52 tp->tm_min = rem / 60;
53 tp->tm_sec = rem % 60;
54 /* January 1, 1970 was a Thursday. */
55 tp->tm_wday = (4 + days) % 7;
56 if (tp->tm_wday < 0)
57 tp->tm_wday += 7;
58 y = 1970;
60 #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
61 #define LEAPS_THRU_END_OF(y) (DIV (y, 4) - DIV (y, 100) + DIV (y, 400))
63 while (days < 0 || days >= (__isleap (y) ? 366 : 365))
65 /* Guess a corrected year, assuming 365 days per year. */
66 time_t yg = y + days / 365 - (days % 365 < 0);
68 /* Adjust DAYS and Y to match the guessed year. */
69 days -= ((yg - y) * 365
70 + LEAPS_THRU_END_OF (yg - 1)
71 - LEAPS_THRU_END_OF (y - 1));
72 y = yg;
74 tp->tm_year = y - 1900;
75 if (tp->tm_year != y - 1900)
77 /* The year cannot be represented due to overflow. */
78 __set_errno (EOVERFLOW);
79 return 0;
81 tp->tm_yday = days;
82 ip = __mon_yday[__isleap(y)];
83 for (y = 11; days < (long int) ip[y]; --y)
84 continue;
85 days -= ip[y];
86 tp->tm_mon = y;
87 tp->tm_mday = days + 1;
88 return 1;