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 size_t strftime(char *restrict s, size_t n, const char *restrict f, const struct tm *restrict tm)
25 for (l=0; *f && l<n; f++) {
35 item = ABDAY_1 + tm->tm_wday;
38 item = DAY_1 + tm->tm_wday;
42 item = ABMON_1 + tm->tm_mon;
45 item = MON_1 + tm->tm_mon;
51 val = (1900+tm->tm_year) / 100;
70 val = 0; //week_based_year(tm)%100;
75 val = 0; //week_based_year(tm);
85 else if (val > 12) val -= 12;
104 item = tm->tm_hour >= 12 ? PM_STR : AM_STR;
123 val = tm->tm_wday ? tm->tm_wday : 7;
127 val = (tm->tm_yday + 7 - tm->tm_wday) / 7;
131 val = (tm->tm_yday + 7 - (tm->tm_wday+6)%7) / 7;
135 val = (tm->tm_yday + 7 - (tm->tm_wday+6)%7) / 7;
136 /* If 1 Jan is just 1-3 days past Monday,
137 * the previous week is also in this year. */
138 if ((tm->tm_wday - tm->tm_yday - 2 + 371) % 7 <= 2)
142 /* If 31 December of prev year a Thursday,
143 * or Friday of a leap year, then the
144 * prev year has 53 weeks. */
145 int dec31 = (tm->tm_wday - tm->tm_yday - 1 + 7) % 7;
146 if (dec31 == 4 || (dec31 == 5 && is_leap(tm->tm_year%400-1)))
148 } else if (val == 53) {
149 /* If 1 January is not a Thursday, and not
150 * a Wednesday of a leap year, then this
151 * year has only 52 weeks. */
152 int jan1 = (tm->tm_wday - tm->tm_yday + 371) % 7;
153 if (jan1 != 4 && (jan1 != 3 || !is_leap(tm->tm_year)))
169 val = tm->tm_year % 100;
173 val = tm->tm_year + 1900;
177 if (tm->tm_isdst < 0) continue;
178 val = -__timezone - (tm->tm_isdst ? __dst_offset : 0);
179 l += snprintf(s+l, n-l, "%+.2d%.2d", val/3600, abs(val%3600)/60);
182 if (tm->tm_isdst < 0 || !__tzname[0] || !__tzname[0][0])
184 l += snprintf(s+l, n-l, "%s", __tzname[!!tm->tm_isdst]);
194 l += snprintf(s+l, n-l, fmt, val);
197 l += snprintf(s+l, n-l, "%s", __langinfo(item));
200 fmt = __langinfo(item);
202 l += strftime(s+l, n-l, fmt, tm);
204 if (l >= n) return 0;