xref: /netbsd-src/lib/libc/time/strftime.c (revision 3b435a73967be44dfb4a27315acd72bfacde430c)
1 /*	$NetBSD: strftime.c,v 1.8 1999/02/07 17:33:30 augustss Exp $	*/
2 
3 /*
4  * Copyright (c) 1989 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #if defined(LIBC_SCCS) && !defined(lint)
38 #if 0
39 static char *sccsid = "@(#)strftime.c	5.11 (Berkeley) 2/24/91";
40 #else
41 __RCSID("$NetBSD: strftime.c,v 1.8 1999/02/07 17:33:30 augustss Exp $");
42 #endif
43 #endif /* LIBC_SCCS and not lint */
44 
45 #include "namespace.h"
46 #include <sys/localedef.h>
47 #include <locale.h>
48 #include <string.h>
49 #include <tzfile.h>
50 #include <time.h>
51 
52 static	int _add __P((const char *, char **, const char *));
53 static	int _conv __P((int, int, int, char **, const char *));
54 static	int _secs __P((const struct tm *, char **, const char *));
55 static	size_t _fmt __P((const char *, const struct tm *, char **,
56 	    const char *));
57 
58 size_t
59 strftime(s, maxsize, format, t)
60 	char *s;
61 	size_t maxsize;
62 	const char *format;
63 	const struct tm *t;
64 {
65 	char *pt;
66 
67 	tzset();
68 	if (maxsize < 1)
69 		return (0);
70 
71 	pt = s;
72 	if (_fmt(format, t, &pt, s + maxsize)) {
73 		*pt = '\0';
74 		return (pt - s);
75 	} else
76 		return (0);
77 }
78 
79 #define SUN_WEEK(t)	(((t)->tm_yday + 7 - \
80 				((t)->tm_wday)) / 7)
81 #define MON_WEEK(t)	(((t)->tm_yday + 7 - \
82 				((t)->tm_wday ? (t)->tm_wday - 1 : 6)) / 7)
83 
84 static size_t
85 _fmt(format, t, pt, ptlim)
86 	const char *format;
87 	const struct tm *t;
88 	char **pt;
89 	const char * const ptlim;
90 {
91 	for (; *format; ++format) {
92 		if (*format == '%') {
93 			++format;
94 			if (*format == 'E') {
95 				/* Alternate Era */
96 				++format;
97 			} else if (*format == 'O') {
98 				/* Alternate numeric symbols */
99 				++format;
100 			}
101 			switch (*format) {
102 			case '\0':
103 				--format;
104 				break;
105 			case 'A':
106 				if (t->tm_wday < 0 || t->tm_wday > 6)
107 					return (0);
108 				if (!_add(_CurrentTimeLocale->day[t->tm_wday],
109 				    pt, ptlim))
110 					return (0);
111 				continue;
112 
113 			case 'a':
114 				if (t->tm_wday < 0 || t->tm_wday > 6)
115 					return (0);
116 				if (!_add(_CurrentTimeLocale->abday[t->tm_wday],
117 				    pt, ptlim))
118 					return (0);
119 				continue;
120 			case 'B':
121 				if (t->tm_mon < 0 || t->tm_mon > 11)
122 					return (0);
123 				if (!_add(_CurrentTimeLocale->mon[t->tm_mon],
124 				    pt, ptlim))
125 					return (0);
126 				continue;
127 			case 'b':
128 			case 'h':
129 				if (t->tm_mon < 0 || t->tm_mon > 11)
130 					return (0);
131 				if (!_add(_CurrentTimeLocale->abmon[t->tm_mon],
132 				    pt, ptlim))
133 					return (0);
134 				continue;
135 			case 'C':
136 				if (!_conv((t->tm_year + TM_YEAR_BASE) / 100,
137 				    2, '0', pt, ptlim))
138 					return (0);
139 				continue;
140 			case 'c':
141 				if (!_fmt(_CurrentTimeLocale->d_t_fmt, t, pt,
142 				    ptlim))
143 					return (0);
144 				continue;
145 			case 'D':
146 				if (!_fmt("%m/%d/%y", t, pt, ptlim))
147 					return (0);
148 				continue;
149 			case 'd':
150 				if (!_conv(t->tm_mday, 2, '0', pt, ptlim))
151 					return (0);
152 				continue;
153 			case 'e':
154 				if (!_conv(t->tm_mday, 2, ' ', pt, ptlim))
155 					return (0);
156 				continue;
157 			case 'H':
158 				if (!_conv(t->tm_hour, 2, '0', pt, ptlim))
159 					return (0);
160 				continue;
161 			case 'I':
162 				if (!_conv(t->tm_hour % 12 ?
163 				    t->tm_hour % 12 : 12, 2, '0', pt, ptlim))
164 					return (0);
165 				continue;
166 			case 'j':
167 				if (!_conv(t->tm_yday + 1, 3, '0', pt, ptlim))
168 					return (0);
169 				continue;
170 			case 'k':
171 				if (!_conv(t->tm_hour, 2, ' ', pt, ptlim))
172 					return (0);
173 				continue;
174 			case 'l':
175 				if (!_conv(t->tm_hour % 12 ?
176 				    t->tm_hour % 12: 12, 2, ' ', pt, ptlim))
177 					return (0);
178 				continue;
179 			case 'M':
180 				if (!_conv(t->tm_min, 2, '0', pt, ptlim))
181 					return (0);
182 				continue;
183 			case 'm':
184 				if (!_conv(t->tm_mon + 1, 2, '0', pt, ptlim))
185 					return (0);
186 				continue;
187 			case 'n':
188 				if (!_add("\n", pt, ptlim))
189 					return (0);
190 				continue;
191 			case 'p':
192 				if (!_add(_CurrentTimeLocale->am_pm[t->tm_hour
193 				    >= 12], pt, ptlim))
194 					return (0);
195 				continue;
196 			case 'R':
197 				if (!_fmt("%H:%M", t, pt, ptlim))
198 					return (0);
199 				continue;
200 			case 'r':
201 				if (!_fmt(_CurrentTimeLocale->t_fmt_ampm, t, pt,
202 				    ptlim))
203 					return (0);
204 				continue;
205 			case 'S':
206 				if (!_conv(t->tm_sec, 2, '0', pt, ptlim))
207 					return (0);
208 				continue;
209 			case 's':
210 				if (!_secs(t, pt, ptlim))
211 					return (0);
212 				continue;
213 			case 'T':
214 				if (!_fmt("%H:%M:%S", t, pt, ptlim))
215 					return (0);
216 				continue;
217 			case 't':
218 				if (!_add("\t", pt, ptlim))
219 					return (0);
220 				continue;
221 			case 'U':
222 				if (!_conv(SUN_WEEK(t), 2, '0', pt, ptlim))
223 					return (0);
224 				continue;
225 			case 'u':
226 				if (!_conv(t->tm_wday ? t->tm_wday : 7, 1, '0',
227 				    pt, ptlim))
228 					return (0);
229 				continue;
230 			case 'V':	/* ISO 8601 week number */
231 			case 'G':	/* ISO 8601 year (four digits) */
232 			case 'g':	/* ISO 8601 year (two digits) */
233 /*
234 ** From Arnold Robbins' strftime version 3.0:  "the week number of the
235 ** year (the first Monday as the first day of week 1) as a decimal number
236 ** (01-53)."
237 ** (ado, 1993-05-24)
238 **
239 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
240 ** "Week 01 of a year is per definition the first week which has the
241 ** Thursday in this year, which is equivalent to the week which contains
242 ** the fourth day of January. In other words, the first week of a new year
243 ** is the week which has the majority of its days in the new year. Week 01
244 ** might also contain days from the previous year and the week before week
245 ** 01 of a year is the last week (52 or 53) of the previous year even if
246 ** it contains days from the new year. A week starts with Monday (day 1)
247 ** and ends with Sunday (day 7).  For example, the first week of the year
248 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
249 ** (ado, 1996-01-02)
250 */
251 				{
252 					int	year;
253 					int	yday;
254 					int	wday;
255 					int	w;
256 
257 					year = t->tm_year + TM_YEAR_BASE;
258 					yday = t->tm_yday;
259 					wday = t->tm_wday;
260 					for ( ; ; ) {
261 						int	len;
262 						int	bot;
263 						int	top;
264 
265 						len = isleap(year) ?
266 							DAYSPERLYEAR :
267 							DAYSPERNYEAR;
268 						/*
269 						** What yday (-3 ... 3) does
270 						** the ISO year begin on?
271 						*/
272 						bot = ((yday + 11 - wday) %
273 							DAYSPERWEEK) - 3;
274 						/*
275 						** What yday does the NEXT
276 						** ISO year begin on?
277 						*/
278 						top = bot -
279 							(len % DAYSPERWEEK);
280 						if (top < -3)
281 							top += DAYSPERWEEK;
282 						top += len;
283 						if (yday >= top) {
284 							++year;
285 							w = 1;
286 							break;
287 						}
288 						if (yday >= bot) {
289 							w = 1 + ((yday - bot) /
290 								DAYSPERWEEK);
291 							break;
292 						}
293 						--year;
294 						yday += isleap(year) ?
295 							DAYSPERLYEAR :
296 							DAYSPERNYEAR;
297 					}
298 #ifdef XPG4_1994_04_09
299 					if ((w == 52
300 					     && t->tm_mon == TM_JANUARY)
301 					    || (w == 1
302 						&& t->tm_mon == TM_DECEMBER))
303 						w = 53;
304 #endif /* defined XPG4_1994_04_09 */
305 					if (*format == 'V') {
306 						if (!_conv(w, 2, '0',
307 							pt, ptlim))
308 							return (0);
309 					} else if (*format == 'g') {
310 						if (!_conv(year % 100, 2, '0',
311 							pt, ptlim))
312 							return (0);
313 					} else	if (!_conv(year, 4, '0',
314 							pt, ptlim))
315 							return (0);
316 				}
317 				continue;
318 			case 'W':
319 				if (!_conv(MON_WEEK(t), 2, '0', pt, ptlim))
320 					return (0);
321 				continue;
322 			case 'w':
323 				if (!_conv(t->tm_wday, 1, '0', pt, ptlim))
324 					return (0);
325 				continue;
326 			case 'x':
327 				if (!_fmt(_CurrentTimeLocale->d_fmt, t, pt,
328 				    ptlim))
329 					return (0);
330 				continue;
331 			case 'X':
332 				if (!_fmt(_CurrentTimeLocale->t_fmt, t, pt,
333 				    ptlim))
334 					return (0);
335 				continue;
336 			case 'y':
337 				if (!_conv((t->tm_year + TM_YEAR_BASE) % 100,
338 				    2, '0', pt, ptlim))
339 					return (0);
340 				continue;
341 			case 'Y':
342 				if (!_conv((t->tm_year + TM_YEAR_BASE), 4, '0',
343 				    pt, ptlim))
344 					return (0);
345 				continue;
346 			case 'Z':
347 				if (tzname[t->tm_isdst ? 1 : 0] &&
348 				    !_add(tzname[t->tm_isdst ? 1 : 0], pt,
349 				    ptlim))
350 					return (0);
351 				continue;
352 			case '%':
353 			/*
354 			 * X311J/88-090 (4.12.3.5): if conversion char is
355 			 * undefined, behavior is undefined.  Print out the
356 			 * character itself as printf(3) does.
357 			 */
358 			default:
359 				break;
360 			}
361 		}
362 		if (*pt == ptlim)
363 			return (0);
364 		*(*pt)++ = *format;
365 	}
366 	return (ptlim - *pt);
367 }
368 
369 static int
370 _secs(t, pt, ptlim)
371 	const struct tm *t;
372 	char **pt;
373 	const char * const ptlim;
374 {
375 	char buf[15];
376 	time_t s;
377 	char *p;
378 	struct tm tmp;
379 
380 	buf[sizeof (buf) - 1] = '\0';
381 	/* Make a copy, mktime(3) modifies the tm struct. */
382 	tmp = *t;
383 	s = mktime(&tmp);
384 	for (p = buf + sizeof(buf) - 2; s > 0 && p > buf; s /= 10)
385 		*p-- = (char)(s % 10 + '0');
386 	return (_add(++p, pt, ptlim));
387 }
388 
389 static int
390 _conv(n, digits, pad, pt, ptlim)
391 	int n, digits;
392 	int pad;
393 	char **pt;
394 	const char * const ptlim;
395 {
396 	char buf[10];
397 	char *p;
398 
399 	buf[sizeof (buf) - 1] = '\0';
400 	for (p = buf + sizeof(buf) - 2; n > 0 && p > buf; n /= 10, --digits)
401 		*p-- = n % 10 + '0';
402 	while (p > buf && digits-- > 0)
403 		*p-- = pad;
404 	return (_add(++p, pt, ptlim));
405 }
406 
407 static int
408 _add(str, pt, ptlim)
409 	const char *str;
410 	char **pt;
411 	const char * const ptlim;
412 {
413 
414 	for (;; ++(*pt)) {
415 		if (*pt == ptlim)
416 			return (0);
417 		if ((**pt = *str++) == '\0')
418 			return (1);
419 	}
420 }
421