9 // FIXME: integer overflows
11 const char *__nl_langinfo_l(nl_item, locale_t);
13 static int is_leap(int y)
16 if (y>INT_MAX-1900) y -= 2000;
18 return !(y%4) && ((y%100) || !(y%400));
21 static int week_num(const struct tm *tm)
23 int val = (tm->tm_yday + 7 - (tm->tm_wday+6)%7) / 7;
24 /* If 1 Jan is just 1-3 days past Monday,
25 * the previous week is also in this year. */
26 if ((tm->tm_wday - tm->tm_yday - 2 + 371) % 7 <= 2)
30 /* If 31 December of prev year a Thursday,
31 * or Friday of a leap year, then the
32 * prev year has 53 weeks. */
33 int dec31 = (tm->tm_wday - tm->tm_yday - 1 + 7) % 7;
34 if (dec31 == 4 || (dec31 == 5 && is_leap(tm->tm_year%400-1)))
36 } else if (val == 53) {
37 /* If 1 January is not a Thursday, and not
38 * a Wednesday of a leap year, then this
39 * year has only 52 weeks. */
40 int jan1 = (tm->tm_wday - tm->tm_yday + 371) % 7;
41 if (jan1 != 4 && (jan1 != 3 || !is_leap(tm->tm_year)))
47 size_t __strftime_l(char *restrict s, size_t n, const char *restrict f, const struct tm *restrict tm, locale_t loc)
53 for (l=0; *f && l<n; f++) {
67 item = ABDAY_1 + tm->tm_wday;
70 item = DAY_1 + tm->tm_wday;
74 item = ABMON_1 + tm->tm_mon;
77 item = MON_1 + tm->tm_mon;
83 val = (1900+tm->tm_year) / 100;
103 val = tm->tm_year + 1900;
104 if (tm->tm_yday < 3 && week_num(tm) != 1) val--;
105 else if (tm->tm_yday > 360 && week_num(tm) == 1) val++;
118 else if (val > 12) val -= 12;
137 item = tm->tm_hour >= 12 ? PM_STR : AM_STR;
156 val = tm->tm_wday ? tm->tm_wday : 7;
160 val = (tm->tm_yday + 7 - tm->tm_wday) / 7;
164 val = (tm->tm_yday + 7 - (tm->tm_wday+6)%7) / 7;
182 val = tm->tm_year % 100;
186 val = tm->tm_year + 1900;
190 val = -tm->__tm_gmtoff;
191 l += snprintf(s+l, n-l, "%+.2d%.2d", val/3600, abs(val%3600)/60);
194 l += snprintf(s+l, n-l, "%s", tm->__tm_zone);
200 l += snprintf(s+l, n-l, fmt, val);
203 l += snprintf(s+l, n-l, "%s", __nl_langinfo_l(item, loc));
206 fmt = __nl_langinfo_l(item, loc);
208 l += __strftime_l(s+l, n-l, fmt, tm, loc);
210 if (l >= n) return 0;
215 size_t strftime(char *restrict s, size_t n, const char *restrict f, const struct tm *restrict tm)
217 return __strftime_l(s, n, f, tm, LC_GLOBAL_LOCALE);
220 weak_alias(__strftime_l, strftime_l);