7 // FIXME: integer overflows
9 const char *__langinfo(nl_item);
11 static int is_leap(int y)
14 if (y>INT_MAX-1900) y -= 2000;
16 return !(y%4) && ((y%100) || !(y%400));
19 static int week_num(const struct tm *tm)
21 int val = (tm->tm_yday + 7 - (tm->tm_wday+6)%7) / 7;
22 /* If 1 Jan is just 1-3 days past Monday,
23 * the previous week is also in this year. */
24 if ((tm->tm_wday - tm->tm_yday - 2 + 371) % 7 <= 2)
28 /* If 31 December of prev year a Thursday,
29 * or Friday of a leap year, then the
30 * prev year has 53 weeks. */
31 int dec31 = (tm->tm_wday - tm->tm_yday - 1 + 7) % 7;
32 if (dec31 == 4 || (dec31 == 5 && is_leap(tm->tm_year%400-1)))
34 } else if (val == 53) {
35 /* If 1 January is not a Thursday, and not
36 * a Wednesday of a leap year, then this
37 * year has only 52 weeks. */
38 int jan1 = (tm->tm_wday - tm->tm_yday + 371) % 7;
39 if (jan1 != 4 && (jan1 != 3 || !is_leap(tm->tm_year)))
45 size_t strftime(char *restrict s, size_t n, const char *restrict f, const struct tm *restrict tm)
51 for (l=0; *f && l<n; f++) {
61 item = ABDAY_1 + tm->tm_wday;
64 item = DAY_1 + tm->tm_wday;
68 item = ABMON_1 + tm->tm_mon;
71 item = MON_1 + tm->tm_mon;
77 val = (1900+tm->tm_year) / 100;
97 val = tm->tm_year + 1900;
98 if (tm->tm_yday < 3 && week_num(tm) != 1) val--;
99 else if (tm->tm_yday > 360 && week_num(tm) == 1) val++;
112 else if (val > 12) val -= 12;
131 item = tm->tm_hour >= 12 ? PM_STR : AM_STR;
150 val = tm->tm_wday ? tm->tm_wday : 7;
154 val = (tm->tm_yday + 7 - tm->tm_wday) / 7;
158 val = (tm->tm_yday + 7 - (tm->tm_wday+6)%7) / 7;
176 val = tm->tm_year % 100;
180 val = tm->tm_year + 1900;
184 val = -tm->__tm_gmtoff;
185 l += snprintf(s+l, n-l, "%+.2d%.2d", val/3600, abs(val%3600)/60);
188 l += snprintf(s+l, n-l, "%s", tm->__tm_zone);
198 l += snprintf(s+l, n-l, fmt, val);
201 l += snprintf(s+l, n-l, "%s", __langinfo(item));
204 fmt = __langinfo(item);
206 l += strftime(s+l, n-l, fmt, tm);
208 if (l >= n) return 0;