strftime.c revision 17209
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#ifdef LIBC_RCS
19static const char rcsid[] =
20	"$Id: strftime.c,v 1.9 1996/07/12 18:55:32 jkh Exp $";
21#endif
22
23#ifndef lint
24#ifndef NOID
25/*
26static char	elsieid[] = "@(#)strftime.c	7.47";
27*/
28/*
29** Based on the UCB version with the ID appearing below.
30** This is ANSIish only when "multibyte character == plain character".
31*/
32#endif /* !defined NOID */
33#endif /* !defined lint */
34
35#include "private.h"
36
37#ifndef LIBC_SCCS
38#ifndef lint
39static const char	sccsid[] = "@(#)strftime.c	5.4 (Berkeley) 3/14/89";
40#endif /* !defined lint */
41#endif /* !defined LIBC_SCCS */
42
43#include "tzfile.h"
44#include <fcntl.h>
45#include <locale.h>
46#include <rune.h>		/* for _PATH_LOCALE */
47#include <sys/stat.h>
48
49struct lc_time_T {
50	const char *	mon[12];
51	const char *	month[12];
52	const char *	wday[7];
53	const char *	weekday[7];
54	const char *	X_fmt;
55	const char *	x_fmt;
56	const char *	c_fmt;
57	const char *	am;
58	const char *	pm;
59	const char *	date_fmt;
60};
61
62static struct lc_time_T		localebuf;
63static int using_locale;
64
65#define Locale	(using_locale ? &localebuf : &C_time_locale)
66
67static const struct lc_time_T	C_time_locale = {
68	{
69		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
70		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
71	}, {
72		"January", "February", "March", "April", "May", "June",
73		"July", "August", "September", "October", "November", "December"
74	}, {
75		"Sun", "Mon", "Tue", "Wed",
76		"Thu", "Fri", "Sat"
77	}, {
78		"Sunday", "Monday", "Tuesday", "Wednesday",
79		"Thursday", "Friday", "Saturday"
80	},
81
82	/* X_fmt */
83	"%H:%M:%S",
84
85	/*
86	** x_fmt
87	** Since the C language standard calls for
88	** "date, using locale's date format," anything goes.
89	** Using just numbers (as here) makes Quakers happier;
90	** it's also compatible with SVR4.
91	*/
92	"%m/%d/%y",
93
94	/*
95	** c_fmt
96	** Note that
97	**	"%a %b %d %H:%M:%S %Y"
98	** is used by Solaris 2.3.
99	*/
100	"%D %X",	/* %m/%d/%y %H:%M:%S */
101
102	/* am */
103	"AM",
104
105	/* pm */
106	"PM",
107
108	/* date_fmt */
109	"%a %b %e %H:%M:%S %Z %Y"
110};
111
112static char *	_add P((const char *, char *, const char *));
113static char *	_conv P((int, const char *, char *, const char *));
114static char *	_fmt P((const char *, const struct tm *, char *, const char *));
115
116size_t strftime P((char *, size_t, const char *, const struct tm *));
117
118extern char *	tzname[];
119
120size_t
121strftime(s, maxsize, format, t)
122char * const		s;
123const size_t		maxsize;
124const char * const	format;
125const struct tm * const	t;
126{
127	char *	p;
128
129	tzset();
130	p = _fmt(((format == NULL) ? "%c" : format), t, s, s + maxsize);
131	if (p == s + maxsize)
132		return 0;
133	*p = '\0';
134	return p - s;
135}
136
137static char *
138_fmt(format, t, pt, ptlim)
139const char *		format;
140const struct tm * const	t;
141char *			pt;
142const char * const	ptlim;
143{
144	for ( ; *format; ++format) {
145		if (*format == '%') {
146label:
147			switch (*++format) {
148			case '\0':
149				--format;
150				break;
151			case 'A':
152				pt = _add((t->tm_wday < 0 || t->tm_wday > 6) ?
153					"?" : Locale->weekday[t->tm_wday],
154					pt, ptlim);
155				continue;
156			case 'a':
157				pt = _add((t->tm_wday < 0 || t->tm_wday > 6) ?
158					"?" : Locale->wday[t->tm_wday],
159					pt, ptlim);
160				continue;
161			case 'B':
162				pt = _add((t->tm_mon < 0 || t->tm_mon > 11) ?
163					"?" : Locale->month[t->tm_mon],
164					pt, ptlim);
165				continue;
166			case 'b':
167			case 'h':
168				pt = _add((t->tm_mon < 0 || t->tm_mon > 11) ?
169					"?" : Locale->mon[t->tm_mon],
170					pt, ptlim);
171				continue;
172			case 'C':
173				/*
174				** %C used to do a...
175				**	_fmt("%a %b %e %X %Y", t);
176				** ...whereas now POSIX 1003.2 calls for
177				** something completely different.
178				** (ado, 5/24/93)
179				*/
180				pt = _conv((t->tm_year + TM_YEAR_BASE) / 100,
181					"%02d", pt, ptlim);
182				continue;
183			case 'c':
184				pt = _fmt(Locale->c_fmt, t, pt, ptlim);
185				continue;
186			case 'D':
187				pt = _fmt("%m/%d/%y", t, pt, ptlim);
188				continue;
189			case 'd':
190				pt = _conv(t->tm_mday, "%02d", pt, ptlim);
191				continue;
192			case 'E':
193			case 'O':
194				/*
195				** POSIX locale extensions, a la
196				** Arnold Robbins' strftime version 3.0.
197				** The sequences
198				**	%Ec %EC %Ex %Ey %EY
199				**	%Od %oe %OH %OI %Om %OM
200				**	%OS %Ou %OU %OV %Ow %OW %Oy
201				** are supposed to provide alternate
202				** representations.
203				** (ado, 5/24/93)
204				*/
205				goto label;
206			case 'e':
207				pt = _conv(t->tm_mday, "%2d", pt, ptlim);
208				continue;
209			case 'H':
210				pt = _conv(t->tm_hour, "%02d", pt, ptlim);
211				continue;
212			case 'I':
213				pt = _conv((t->tm_hour % 12) ?
214					(t->tm_hour % 12) : 12,
215					"%02d", pt, ptlim);
216				continue;
217			case 'j':
218				pt = _conv(t->tm_yday + 1, "%03d", pt, ptlim);
219				continue;
220			case 'k':
221				/*
222				** This used to be...
223				**	_conv(t->tm_hour % 12 ?
224				**		t->tm_hour % 12 : 12, 2, ' ');
225				** ...and has been changed to the below to
226				** match SunOS 4.1.1 and Arnold Robbins'
227				** strftime version 3.0.  That is, "%k" and
228				** "%l" have been swapped.
229				** (ado, 5/24/93)
230				*/
231				pt = _conv(t->tm_hour, "%2d", pt, ptlim);
232				continue;
233#ifdef KITCHEN_SINK
234			case 'K':
235				/*
236				** After all this time, still unclaimed!
237				*/
238				pt = _add("kitchen sink", pt, ptlim);
239				continue;
240#endif /* defined KITCHEN_SINK */
241			case 'l':
242				/*
243				** This used to be...
244				**	_conv(t->tm_hour, 2, ' ');
245				** ...and has been changed to the below to
246				** match SunOS 4.1.1 and Arnold Robbin's
247				** strftime version 3.0.  That is, "%k" and
248				** "%l" have been swapped.
249				** (ado, 5/24/93)
250				*/
251				pt = _conv((t->tm_hour % 12) ?
252					(t->tm_hour % 12) : 12,
253					"%2d", pt, ptlim);
254				continue;
255			case 'M':
256				pt = _conv(t->tm_min, "%02d", pt, ptlim);
257				continue;
258			case 'm':
259				pt = _conv(t->tm_mon + 1, "%02d", pt, ptlim);
260				continue;
261			case 'n':
262				pt = _add("\n", pt, ptlim);
263				continue;
264			case 'p':
265				pt = _add((t->tm_hour >= 12) ?
266					Locale->pm :
267					Locale->am,
268					pt, ptlim);
269				continue;
270			case 'R':
271				pt = _fmt("%H:%M", t, pt, ptlim);
272				continue;
273			case 'r':
274				pt = _fmt("%I:%M:%S %p", t, pt, ptlim);
275				continue;
276			case 'S':
277				pt = _conv(t->tm_sec, "%02d", pt, ptlim);
278				continue;
279			case 's':
280				{
281					struct tm	tm;
282					char		buf[INT_STRLEN_MAXIMUM(
283								time_t) + 1];
284					time_t		mkt;
285
286					tm = *t;
287					mkt = mktime(&tm);
288					if (TYPE_SIGNED(time_t))
289						(void) sprintf(buf, "%ld",
290							(long) mkt);
291					else	(void) sprintf(buf, "%lu",
292							(unsigned long) mkt);
293					pt = _add(buf, pt, ptlim);
294				}
295				continue;
296			case 'T':
297				pt = _fmt("%H:%M:%S", t, pt, ptlim);
298				continue;
299			case 't':
300				pt = _add("\t", pt, ptlim);
301				continue;
302			case 'U':
303				pt = _conv((t->tm_yday + 7 - t->tm_wday) / 7,
304					"%02d", pt, ptlim);
305				continue;
306			case 'u':
307				/*
308				** From Arnold Robbins' strftime version 3.0:
309				** "ISO 8601: Weekday as a decimal number
310				** [1 (Monday) - 7]"
311				** (ado, 5/24/93)
312				*/
313				pt = _conv((t->tm_wday == 0) ? 7 : t->tm_wday,
314					"%d", pt, ptlim);
315				continue;
316			case 'V':	/* ISO 8601 week number */
317			case 'G':	/* ISO 8601 year (four digits) */
318			case 'g':	/* ISO 8601 year (two digits) */
319/*
320** From Arnold Robbins' strftime version 3.0:  "the week number of the
321** year (the first Monday as the first day of week 1) as a decimal number
322** (01-53)."
323** (ado, 1993-05-24)
324**
325** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
326** "Week 01 of a year is per definition the first week which has the
327** Thursday in this year, which is equivalent to the week which contains
328** the fourth day of January. In other words, the first week of a new year
329** is the week which has the majority of its days in the new year. Week 01
330** might also contain days from the previous year and the week before week
331** 01 of a year is the last week (52 or 53) of the previous year even if
332** it contains days from the new year. A week starts with Monday (day 1)
333** and ends with Sunday (day 7).  For example, the first week of the year
334** 1997 lasts from 1996-12-30 to 1997-01-05..."
335** (ado, 1996-01-02)
336*/
337				{
338					int	year;
339					int	yday;
340					int	wday;
341					int	w;
342
343					year = t->tm_year + TM_YEAR_BASE;
344					yday = t->tm_yday;
345					wday = t->tm_wday;
346					for ( ; ; ) {
347						int	len;
348						int	bot;
349						int	top;
350
351						len = isleap(year) ?
352							DAYSPERLYEAR :
353							DAYSPERNYEAR;
354						/*
355						** What yday (-3 ... 3) does
356						** the ISO year begin on?
357						*/
358						bot = ((yday + 11 - wday) %
359							DAYSPERWEEK) - 3;
360						/*
361						** What yday does the NEXT
362						** ISO year begin on?
363						*/
364						top = bot -
365							(len % DAYSPERWEEK);
366						if (top < -3)
367							top += DAYSPERWEEK;
368						top += len;
369						if (yday >= top) {
370							++year;
371							w = 1;
372							break;
373						}
374						if (yday >= bot) {
375							w = 1 + ((yday - bot) /
376								DAYSPERWEEK);
377							break;
378						}
379						--year;
380						yday += isleap(year) ?
381							DAYSPERLYEAR :
382							DAYSPERNYEAR;
383					}
384#ifdef XPG4_1994_04_09
385					if (w == 52 && t->tm_mon == TM_JANUARY)
386						w = 53;
387#endif /* defined XPG4_1994_04_09 */
388					if (*format == 'V')
389						pt = _conv(w, "%02d",
390							pt, ptlim);
391					else if (*format == 'G')
392						pt = _conv(year, "%02d",
393							pt, ptlim);
394					else	pt = _conv(year, "%04d",
395							pt, ptlim);
396				}
397				continue;
398			case 'v':
399				/*
400				** From Arnold Robbins' strftime version 3.0:
401				** "date as dd-bbb-YYYY"
402				** (ado, 5/24/93)
403				*/
404				pt = _fmt("%e-%b-%Y", t, pt, ptlim);
405				continue;
406			case 'W':
407				pt = _conv((t->tm_yday + 7 -
408					(t->tm_wday ?
409					(t->tm_wday - 1) : 6)) / 7,
410					"%02d", pt, ptlim);
411				continue;
412			case 'w':
413				pt = _conv(t->tm_wday, "%d", pt, ptlim);
414				continue;
415			case 'X':
416				pt = _fmt(Locale->X_fmt, t, pt, ptlim);
417				continue;
418			case 'x':
419				pt = _fmt(Locale->x_fmt, t, pt, ptlim);
420				continue;
421			case 'y':
422				pt = _conv((t->tm_year + TM_YEAR_BASE) % 100,
423					"%02d", pt, ptlim);
424				continue;
425			case 'Y':
426				pt = _conv(t->tm_year + TM_YEAR_BASE, "%04d",
427					pt, ptlim);
428				continue;
429			case 'Z':
430				if (t->tm_zone != NULL)
431					pt = _add(t->tm_zone, pt, ptlim);
432				else
433				if (t->tm_isdst == 0 || t->tm_isdst == 1) {
434					pt = _add(tzname[t->tm_isdst],
435						pt, ptlim);
436				} else  pt = _add("?", pt, ptlim);
437				continue;
438			case '+':
439				pt = _fmt(Locale->date_fmt, t, pt, ptlim);
440				continue;
441			case '%':
442			/*
443			 * X311J/88-090 (4.12.3.5): if conversion char is
444			 * undefined, behavior is undefined.  Print out the
445			 * character itself as printf(3) also does.
446			 */
447			default:
448				break;
449			}
450		}
451		if (pt == ptlim)
452			break;
453		*pt++ = *format;
454	}
455	return pt;
456}
457
458static char *
459_conv(n, format, pt, ptlim)
460const int		n;
461const char * const	format;
462char * const		pt;
463const char * const	ptlim;
464{
465	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
466
467	(void) sprintf(buf, format, n);
468	return _add(buf, pt, ptlim);
469}
470
471static char *
472_secs(t, pt, ptlim)
473	const struct tm *t;
474	char *pt;
475	const char *ptlim;
476{
477	char    buf[INT_STRLEN_MAXIMUM(int) + 1];
478	register time_t s;
479	struct tm tmp;
480
481	/* Make a copy, mktime(3) modifies the tm struct. */
482	tmp = *t;
483	s = mktime(&tmp);
484	(void) sprintf(buf, "%ld", s);
485	return _add(buf, pt, ptlim);
486}
487
488static char *
489_add(str, pt, ptlim)
490const char *		str;
491char *			pt;
492const char * const	ptlim;
493{
494	while (pt < ptlim && (*pt = *str++) != '\0')
495		++pt;
496	return pt;
497}
498
499extern char *_PathLocale;
500
501int
502__time_load_locale(const char *name)
503{
504	static const char	lc_time[] = "LC_TIME";
505	static char *		locale_buf;
506	static char		locale_buf_C[] = "C";
507
508	int			fd;
509	char *			lbuf;
510	char *			p;
511	const char **		ap;
512	const char *		plim;
513	char			filename[FILENAME_MAX];
514	struct stat		st;
515	size_t			namesize;
516	size_t			bufsize;
517	int                     save_using_locale;
518
519	save_using_locale = using_locale;
520	using_locale = 0;
521
522	if (name == NULL)
523		goto no_locale;
524
525	if (!*name || !strcmp(name, "C") || !strcmp(name, "POSIX"))
526		return 0;
527
528	/*
529	** If the locale name is the same as our cache, use the cache.
530	*/
531	lbuf = locale_buf;
532	if (lbuf != NULL && strcmp(name, lbuf) == 0) {
533		p = lbuf;
534		for (ap = (const char **) &localebuf;
535			ap < (const char **) (&localebuf + 1);
536				++ap)
537					*ap = p += strlen(p) + 1;
538		using_locale = 1;
539		return 0;
540	}
541	/*
542	** Slurp the locale file into the cache.
543	*/
544	namesize = strlen(name) + 1;
545
546	snprintf(filename, sizeof filename,
547		 "%s/%s/%s",
548		 _PathLocale, name, lc_time);
549	fd = open(filename, O_RDONLY);
550	if (fd < 0)
551		goto no_locale;
552	if (fstat(fd, &st) != 0)
553		goto bad_locale;
554	if (st.st_size <= 0)
555		goto bad_locale;
556	bufsize = namesize + st.st_size;
557	locale_buf = NULL;
558	lbuf = (lbuf == NULL || lbuf == locale_buf_C) ?
559		malloc(bufsize) : realloc(lbuf, bufsize);
560	if (lbuf == NULL)
561		goto bad_locale;
562	(void) strcpy(lbuf, name);
563	p = lbuf + namesize;
564	plim = p + st.st_size;
565	if (read(fd, p, (size_t) st.st_size) != st.st_size)
566		goto bad_lbuf;
567	if (close(fd) != 0)
568		goto bad_lbuf;
569	/*
570	** Parse the locale file into localebuf.
571	*/
572	if (plim[-1] != '\n')
573		goto bad_lbuf;
574	for (ap = (const char **) &localebuf;
575		ap < (const char **) (&localebuf + 1);
576			++ap) {
577				if (p == plim)
578					goto reset_locale;
579				*ap = p;
580				while (*p != '\n')
581					++p;
582				*p++ = '\0';
583	}
584	/*
585	** Record the successful parse in the cache.
586	*/
587	locale_buf = lbuf;
588
589	using_locale = 1;
590	return 0;
591
592reset_locale:
593	/*
594	 * XXX - This may not be the correct thing to do in this case.
595	 * setlocale() assumes that we left the old locale alone.
596	 */
597	locale_buf = locale_buf_C;
598	localebuf = C_time_locale;
599	save_using_locale = 0;
600bad_lbuf:
601	free(lbuf);
602bad_locale:
603	(void) close(fd);
604no_locale:
605	using_locale = save_using_locale;
606	return -1;
607}
608