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