xref: /freebsd/lib/libc/stdtime/strftime.c (revision 2be1a816b9ff69588e55be0a84cbe2a31efc0f2f)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 #ifndef NOID
20 static const char	elsieid[] = "@(#)strftime.c	7.64";
21 /*
22 ** Based on the UCB version with the ID appearing below.
23 ** This is ANSIish only when "multibyte character == plain character".
24 */
25 #endif /* !defined NOID */
26 #endif /* !defined lint */
27 
28 #include "namespace.h"
29 #include "private.h"
30 
31 #if defined(LIBC_SCCS) && !defined(lint)
32 static const char	sccsid[] = "@(#)strftime.c	5.4 (Berkeley) 3/14/89";
33 #endif /* LIBC_SCCS and not lint */
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "tzfile.h"
38 #include <fcntl.h>
39 #include <sys/stat.h>
40 #include "un-namespace.h"
41 #include "timelocal.h"
42 
43 static char *	_add(const char *, char *, const char *);
44 static char *	_conv(int, const char *, char *, const char *);
45 static char *	_fmt(const char *, const struct tm *, char *, const char *, int *);
46 
47 size_t strftime(char * __restrict, size_t, const char * __restrict,
48     const struct tm * __restrict);
49 
50 extern char *	tzname[];
51 
52 #ifndef YEAR_2000_NAME
53 #define YEAR_2000_NAME	"CHECK_STRFTIME_FORMATS_FOR_TWO_DIGIT_YEARS"
54 #endif /* !defined YEAR_2000_NAME */
55 
56 
57 #define IN_NONE	0
58 #define IN_SOME	1
59 #define IN_THIS	2
60 #define IN_ALL	3
61 
62 #define PAD_DEFAULT 0
63 #define PAD_LESS	1
64 #define PAD_SPACE	2
65 #define PAD_ZERO	3
66 
67 static const char* fmt_padding[][4] = {
68 	/* DEFAULT,	LESS,	SPACE,	ZERO */
69 #define PAD_FMT_MONTHDAY	0
70 #define PAD_FMT_HMS			0
71 #define PAD_FMT_CENTURY		0
72 #define PAD_FMT_SHORTYEAR	0
73 #define PAD_FMT_MONTH		0
74 #define PAD_FMT_WEEKOFYEAR	0
75 #define PAD_FMT_DAYOFMONTH	0
76 	{ "%02d",	"%d",	"%2d",	"%02d" },
77 #define PAD_FMT_SDAYOFMONTH	1
78 #define PAD_FMT_SHMS		1
79 	{ "%2d",	"%d",	"%2d",	"%02d" },
80 #define	PAD_FMT_DAYOFYEAR	2
81 	{ "%03d",	"%d",	"%3d",	"%03d" },
82 #define PAD_FMT_YEAR		3
83 	{ "%04d",	"%d",	"%4d",	"%04d" }
84 };
85 
86 size_t
87 strftime(char * __restrict s, size_t maxsize, const char * __restrict format,
88     const struct tm * __restrict t)
89 {
90 	char *	p;
91 	int	warn;
92 
93 	tzset();
94 	warn = IN_NONE;
95 	p = _fmt(((format == NULL) ? "%c" : format), t, s, s + maxsize, &warn);
96 #ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
97 	if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
98 		(void) fprintf(stderr, "\n");
99 		if (format == NULL)
100 			(void) fprintf(stderr, "NULL strftime format ");
101 		else	(void) fprintf(stderr, "strftime format \"%s\" ",
102 				format);
103 		(void) fprintf(stderr, "yields only two digits of years in ");
104 		if (warn == IN_SOME)
105 			(void) fprintf(stderr, "some locales");
106 		else if (warn == IN_THIS)
107 			(void) fprintf(stderr, "the current locale");
108 		else	(void) fprintf(stderr, "all locales");
109 		(void) fprintf(stderr, "\n");
110 	}
111 #endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
112 	if (p == s + maxsize)
113 		return 0;
114 	*p = '\0';
115 	return p - s;
116 }
117 
118 static char *
119 _fmt(format, t, pt, ptlim, warnp)
120 const char *		format;
121 const struct tm * const	t;
122 char *			pt;
123 const char * const	ptlim;
124 int *			warnp;
125 {
126 	int Ealternative, Oalternative, PadIndex;
127 	struct lc_time_T *tptr = __get_current_time_locale();
128 
129 	for ( ; *format; ++format) {
130 		if (*format == '%') {
131 			Ealternative = 0;
132 			Oalternative = 0;
133 			PadIndex	 = PAD_DEFAULT;
134 label:
135 			switch (*++format) {
136 			case '\0':
137 				--format;
138 				break;
139 			case 'A':
140 				pt = _add((t->tm_wday < 0 ||
141 					t->tm_wday >= DAYSPERWEEK) ?
142 					"?" : tptr->weekday[t->tm_wday],
143 					pt, ptlim);
144 				continue;
145 			case 'a':
146 				pt = _add((t->tm_wday < 0 ||
147 					t->tm_wday >= DAYSPERWEEK) ?
148 					"?" : tptr->wday[t->tm_wday],
149 					pt, ptlim);
150 				continue;
151 			case 'B':
152 				pt = _add((t->tm_mon < 0 ||
153 					t->tm_mon >= MONSPERYEAR) ?
154 					"?" : (Oalternative ? tptr->alt_month :
155 					tptr->month)[t->tm_mon],
156 					pt, ptlim);
157 				continue;
158 			case 'b':
159 			case 'h':
160 				pt = _add((t->tm_mon < 0 ||
161 					t->tm_mon >= MONSPERYEAR) ?
162 					"?" : tptr->mon[t->tm_mon],
163 					pt, ptlim);
164 				continue;
165 			case 'C':
166 				/*
167 				** %C used to do a...
168 				**	_fmt("%a %b %e %X %Y", t);
169 				** ...whereas now POSIX 1003.2 calls for
170 				** something completely different.
171 				** (ado, 1993-05-24)
172 				*/
173 				pt = _conv((t->tm_year + TM_YEAR_BASE) / 100,
174 					fmt_padding[PAD_FMT_CENTURY][PadIndex], pt, ptlim);
175 				continue;
176 			case 'c':
177 				{
178 				int warn2 = IN_SOME;
179 
180 				pt = _fmt(tptr->c_fmt, t, pt, ptlim, warnp);
181 				if (warn2 == IN_ALL)
182 					warn2 = IN_THIS;
183 				if (warn2 > *warnp)
184 					*warnp = warn2;
185 				}
186 				continue;
187 			case 'D':
188 				pt = _fmt("%m/%d/%y", t, pt, ptlim, warnp);
189 				continue;
190 			case 'd':
191 				pt = _conv(t->tm_mday, fmt_padding[PAD_FMT_DAYOFMONTH][PadIndex],
192 					pt, ptlim);
193 				continue;
194 			case 'E':
195 				if (Ealternative || Oalternative)
196 					break;
197 				Ealternative++;
198 				goto label;
199 			case 'O':
200 				/*
201 				** C99 locale modifiers.
202 				** The sequences
203 				**	%Ec %EC %Ex %EX %Ey %EY
204 				**	%Od %oe %OH %OI %Om %OM
205 				**	%OS %Ou %OU %OV %Ow %OW %Oy
206 				** are supposed to provide alternate
207 				** representations.
208 				**
209 				** FreeBSD extension
210 				**      %OB
211 				*/
212 				if (Ealternative || Oalternative)
213 					break;
214 				Oalternative++;
215 				goto label;
216 			case 'e':
217 				pt = _conv(t->tm_mday,
218 					fmt_padding[PAD_FMT_SDAYOFMONTH][PadIndex], pt, ptlim);
219 				continue;
220 			case 'F':
221 				pt = _fmt("%Y-%m-%d", t, pt, ptlim, warnp);
222 				continue;
223 			case 'H':
224 				pt = _conv(t->tm_hour, fmt_padding[PAD_FMT_HMS][PadIndex],
225 					pt, ptlim);
226 				continue;
227 			case 'I':
228 				pt = _conv((t->tm_hour % 12) ?
229 					(t->tm_hour % 12) : 12,
230 					fmt_padding[PAD_FMT_HMS][PadIndex], pt, ptlim);
231 				continue;
232 			case 'j':
233 				pt = _conv(t->tm_yday + 1,
234 					fmt_padding[PAD_FMT_DAYOFYEAR][PadIndex], pt, ptlim);
235 				continue;
236 			case 'k':
237 				/*
238 				** This used to be...
239 				**	_conv(t->tm_hour % 12 ?
240 				**		t->tm_hour % 12 : 12, 2, ' ');
241 				** ...and has been changed to the below to
242 				** match SunOS 4.1.1 and Arnold Robbins'
243 				** strftime version 3.0.  That is, "%k" and
244 				** "%l" have been swapped.
245 				** (ado, 1993-05-24)
246 				*/
247 				pt = _conv(t->tm_hour, fmt_padding[PAD_FMT_SHMS][PadIndex],
248 					pt, ptlim);
249 				continue;
250 #ifdef KITCHEN_SINK
251 			case 'K':
252 				/*
253 				** After all this time, still unclaimed!
254 				*/
255 				pt = _add("kitchen sink", pt, ptlim);
256 				continue;
257 #endif /* defined KITCHEN_SINK */
258 			case 'l':
259 				/*
260 				** This used to be...
261 				**	_conv(t->tm_hour, 2, ' ');
262 				** ...and has been changed to the below to
263 				** match SunOS 4.1.1 and Arnold Robbin's
264 				** strftime version 3.0.  That is, "%k" and
265 				** "%l" have been swapped.
266 				** (ado, 1993-05-24)
267 				*/
268 				pt = _conv((t->tm_hour % 12) ?
269 					(t->tm_hour % 12) : 12,
270 					fmt_padding[PAD_FMT_SHMS][PadIndex], pt, ptlim);
271 				continue;
272 			case 'M':
273 				pt = _conv(t->tm_min, fmt_padding[PAD_FMT_HMS][PadIndex],
274 					pt, ptlim);
275 				continue;
276 			case 'm':
277 				pt = _conv(t->tm_mon + 1,
278 					fmt_padding[PAD_FMT_MONTH][PadIndex], pt, ptlim);
279 				continue;
280 			case 'n':
281 				pt = _add("\n", pt, ptlim);
282 				continue;
283 			case 'p':
284 				pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
285 					tptr->pm :
286 					tptr->am,
287 					pt, ptlim);
288 				continue;
289 			case 'R':
290 				pt = _fmt("%H:%M", t, pt, ptlim, warnp);
291 				continue;
292 			case 'r':
293 				pt = _fmt(tptr->ampm_fmt, t, pt, ptlim,
294 					warnp);
295 				continue;
296 			case 'S':
297 				pt = _conv(t->tm_sec, fmt_padding[PAD_FMT_HMS][PadIndex],
298 					pt, ptlim);
299 				continue;
300 			case 's':
301 				{
302 					struct tm	tm;
303 					char		buf[INT_STRLEN_MAXIMUM(
304 								time_t) + 1];
305 					time_t		mkt;
306 
307 					tm = *t;
308 					mkt = mktime(&tm);
309 					if (TYPE_SIGNED(time_t))
310 						(void) sprintf(buf, "%ld",
311 							(long) mkt);
312 					else	(void) sprintf(buf, "%lu",
313 							(unsigned long) mkt);
314 					pt = _add(buf, pt, ptlim);
315 				}
316 				continue;
317 			case 'T':
318 				pt = _fmt("%H:%M:%S", t, pt, ptlim, warnp);
319 				continue;
320 			case 't':
321 				pt = _add("\t", pt, ptlim);
322 				continue;
323 			case 'U':
324 				pt = _conv((t->tm_yday + DAYSPERWEEK -
325 					t->tm_wday) / DAYSPERWEEK,
326 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex], pt, ptlim);
327 				continue;
328 			case 'u':
329 				/*
330 				** From Arnold Robbins' strftime version 3.0:
331 				** "ISO 8601: Weekday as a decimal number
332 				** [1 (Monday) - 7]"
333 				** (ado, 1993-05-24)
334 				*/
335 				pt = _conv((t->tm_wday == 0) ?
336 					DAYSPERWEEK : t->tm_wday,
337 					"%d", pt, ptlim);
338 				continue;
339 			case 'V':	/* ISO 8601 week number */
340 			case 'G':	/* ISO 8601 year (four digits) */
341 			case 'g':	/* ISO 8601 year (two digits) */
342 /*
343 ** From Arnold Robbins' strftime version 3.0:  "the week number of the
344 ** year (the first Monday as the first day of week 1) as a decimal number
345 ** (01-53)."
346 ** (ado, 1993-05-24)
347 **
348 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
349 ** "Week 01 of a year is per definition the first week which has the
350 ** Thursday in this year, which is equivalent to the week which contains
351 ** the fourth day of January. In other words, the first week of a new year
352 ** is the week which has the majority of its days in the new year. Week 01
353 ** might also contain days from the previous year and the week before week
354 ** 01 of a year is the last week (52 or 53) of the previous year even if
355 ** it contains days from the new year. A week starts with Monday (day 1)
356 ** and ends with Sunday (day 7).  For example, the first week of the year
357 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
358 ** (ado, 1996-01-02)
359 */
360 				{
361 					int	year;
362 					int	yday;
363 					int	wday;
364 					int	w;
365 
366 					year = t->tm_year + TM_YEAR_BASE;
367 					yday = t->tm_yday;
368 					wday = t->tm_wday;
369 					for ( ; ; ) {
370 						int	len;
371 						int	bot;
372 						int	top;
373 
374 						len = isleap(year) ?
375 							DAYSPERLYEAR :
376 							DAYSPERNYEAR;
377 						/*
378 						** What yday (-3 ... 3) does
379 						** the ISO year begin on?
380 						*/
381 						bot = ((yday + 11 - wday) %
382 							DAYSPERWEEK) - 3;
383 						/*
384 						** What yday does the NEXT
385 						** ISO year begin on?
386 						*/
387 						top = bot -
388 							(len % DAYSPERWEEK);
389 						if (top < -3)
390 							top += DAYSPERWEEK;
391 						top += len;
392 						if (yday >= top) {
393 							++year;
394 							w = 1;
395 							break;
396 						}
397 						if (yday >= bot) {
398 							w = 1 + ((yday - bot) /
399 								DAYSPERWEEK);
400 							break;
401 						}
402 						--year;
403 						yday += isleap(year) ?
404 							DAYSPERLYEAR :
405 							DAYSPERNYEAR;
406 					}
407 #ifdef XPG4_1994_04_09
408 					if ((w == 52
409 					     && t->tm_mon == TM_JANUARY)
410 					    || (w == 1
411 						&& t->tm_mon == TM_DECEMBER))
412 						w = 53;
413 #endif /* defined XPG4_1994_04_09 */
414 					if (*format == 'V')
415 						pt = _conv(w, fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex],
416 							pt, ptlim);
417 					else if (*format == 'g') {
418 						*warnp = IN_ALL;
419 						pt = _conv(year % 100, fmt_padding[PAD_FMT_SHORTYEAR][PadIndex],
420 							pt, ptlim);
421 					} else	pt = _conv(year, fmt_padding[PAD_FMT_YEAR][PadIndex],
422 							pt, ptlim);
423 				}
424 				continue;
425 			case 'v':
426 				/*
427 				** From Arnold Robbins' strftime version 3.0:
428 				** "date as dd-bbb-YYYY"
429 				** (ado, 1993-05-24)
430 				*/
431 				pt = _fmt("%e-%b-%Y", t, pt, ptlim, warnp);
432 				continue;
433 			case 'W':
434 				pt = _conv((t->tm_yday + DAYSPERWEEK -
435 					(t->tm_wday ?
436 					(t->tm_wday - 1) :
437 					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
438 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex], pt, ptlim);
439 				continue;
440 			case 'w':
441 				pt = _conv(t->tm_wday, "%d", pt, ptlim);
442 				continue;
443 			case 'X':
444 				pt = _fmt(tptr->X_fmt, t, pt, ptlim, warnp);
445 				continue;
446 			case 'x':
447 				{
448 				int	warn2 = IN_SOME;
449 
450 				pt = _fmt(tptr->x_fmt, t, pt, ptlim, &warn2);
451 				if (warn2 == IN_ALL)
452 					warn2 = IN_THIS;
453 				if (warn2 > *warnp)
454 					*warnp = warn2;
455 				}
456 				continue;
457 			case 'y':
458 				*warnp = IN_ALL;
459 				pt = _conv((t->tm_year + TM_YEAR_BASE) % 100,
460 					fmt_padding[PAD_FMT_SHORTYEAR][PadIndex], pt, ptlim);
461 				continue;
462 			case 'Y':
463 				pt = _conv(t->tm_year + TM_YEAR_BASE,
464 					fmt_padding[PAD_FMT_YEAR][PadIndex],
465 					pt, ptlim);
466 				continue;
467 			case 'Z':
468 #ifdef TM_ZONE
469 				if (t->TM_ZONE != NULL)
470 					pt = _add(t->TM_ZONE, pt, ptlim);
471 				else
472 #endif /* defined TM_ZONE */
473 				if (t->tm_isdst >= 0)
474 					pt = _add(tzname[t->tm_isdst != 0],
475 						pt, ptlim);
476 				/*
477 				** C99 says that %Z must be replaced by the
478 				** empty string if the time zone is not
479 				** determinable.
480 				*/
481 				continue;
482 			case 'z':
483 				{
484 				int		diff;
485 				char const *	sign;
486 
487 				if (t->tm_isdst < 0)
488 					continue;
489 #ifdef TM_GMTOFF
490 				diff = t->TM_GMTOFF;
491 #else /* !defined TM_GMTOFF */
492 				/*
493 				** C99 says that the UTC offset must
494 				** be computed by looking only at
495 				** tm_isdst.  This requirement is
496 				** incorrect, since it means the code
497 				** must rely on magic (in this case
498 				** altzone and timezone), and the
499 				** magic might not have the correct
500 				** offset.  Doing things correctly is
501 				** tricky and requires disobeying C99;
502 				** see GNU C strftime for details.
503 				** For now, punt and conform to the
504 				** standard, even though it's incorrect.
505 				**
506 				** C99 says that %z must be replaced by the
507 				** empty string if the time zone is not
508 				** determinable, so output nothing if the
509 				** appropriate variables are not available.
510 				*/
511 				if (t->tm_isdst == 0)
512 #ifdef USG_COMPAT
513 					diff = -timezone;
514 #else /* !defined USG_COMPAT */
515 					continue;
516 #endif /* !defined USG_COMPAT */
517 				else
518 #ifdef ALTZONE
519 					diff = -altzone;
520 #else /* !defined ALTZONE */
521 					continue;
522 #endif /* !defined ALTZONE */
523 #endif /* !defined TM_GMTOFF */
524 				if (diff < 0) {
525 					sign = "-";
526 					diff = -diff;
527 				} else	sign = "+";
528 				pt = _add(sign, pt, ptlim);
529 				diff /= 60;
530 				pt = _conv((diff/60)*100 + diff%60,
531 					fmt_padding[PAD_FMT_YEAR][PadIndex], pt, ptlim);
532 				}
533 				continue;
534 			case '+':
535 				pt = _fmt(tptr->date_fmt, t, pt, ptlim,
536 					warnp);
537 				continue;
538 			case '-':
539 				if (PadIndex != PAD_DEFAULT)
540 					break;
541 				PadIndex = PAD_LESS;
542 				goto label;
543 			case '_':
544 				if (PadIndex != PAD_DEFAULT)
545 					break;
546 				PadIndex = PAD_SPACE;
547 				goto label;
548 			case '0':
549 				if (PadIndex != PAD_DEFAULT)
550 					break;
551 				PadIndex = PAD_ZERO;
552 				goto label;
553 			case '%':
554 			/*
555 			** X311J/88-090 (4.12.3.5): if conversion char is
556 			** undefined, behavior is undefined.  Print out the
557 			** character itself as printf(3) also does.
558 			*/
559 			default:
560 				break;
561 			}
562 		}
563 		if (pt == ptlim)
564 			break;
565 		*pt++ = *format;
566 	}
567 	return pt;
568 }
569 
570 static char *
571 _conv(n, format, pt, ptlim)
572 const int		n;
573 const char * const	format;
574 char * const		pt;
575 const char * const	ptlim;
576 {
577 	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
578 
579 	(void) sprintf(buf, format, n);
580 	return _add(buf, pt, ptlim);
581 }
582 
583 static char *
584 _add(str, pt, ptlim)
585 const char *		str;
586 char *			pt;
587 const char * const	ptlim;
588 {
589 	while (pt < ptlim && (*pt = *str++) != '\0')
590 		++pt;
591 	return pt;
592 }
593