2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1985, 1987, 1988, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/param.h>
51 #define TM_YEAR_BASE 1900
54 static void badformat(void);
55 static void iso8601_usage(const char *) __dead2;
56 static void multipleformats(void);
57 static void printdate(const char *);
58 static void printisodate(struct tm *, long);
59 static void setthetime(const char *, const char *, int, struct timespec *);
60 static size_t strftime_ns(char * __restrict, size_t, const char * __restrict,
61 const struct tm * __restrict, long);
62 static void usage(void) __dead2;
64 static const struct iso8601_fmt {
66 const char *format_string;
68 { "date", "%Y-%m-%d" },
74 static const struct iso8601_fmt *iso8601_selected;
76 static const char *rfc2822_format = "%a, %d %b %Y %T %z";
79 main(int argc, char *argv[])
83 bool Iflag, jflag, Rflag;
86 char *fmt, *outzone = NULL;
89 const struct vary *badv;
96 (void) setlocale(LC_TIME, "");
98 Iflag = jflag = Rflag = 0;
101 while ((ch = getopt(argc, argv, "f:I::jnRr:uv:z:")) != -1)
110 if (optarg == NULL) {
111 iso8601_selected = iso8601_fmts;
114 for (i = 0; i < nitems(iso8601_fmts); i++)
115 if (strcmp(optarg, iso8601_fmts[i].refname) == 0)
117 if (i == nitems(iso8601_fmts))
118 iso8601_usage(optarg);
120 iso8601_selected = &iso8601_fmts[i];
123 jflag = 1; /* don't set time */
127 case 'R': /* RFC 2822 datetime format */
132 case 'r': /* user specified seconds */
134 ts.tv_sec = strtoq(optarg, &tmp, 0);
136 if (stat(optarg, &sb) == 0) {
137 ts.tv_sec = sb.st_mtim.tv_sec;
138 ts.tv_nsec = sb.st_mtim.tv_nsec;
143 case 'u': /* do everything in UTC */
144 (void)setenv("TZ", "UTC0", 1);
150 v = vary_append(v, optarg);
158 if (!rflag && clock_gettime(CLOCK_REALTIME, &ts) == -1)
159 err(1, "clock_gettime");
164 format = rfc2822_format;
166 /* allow the operands in any order */
167 if (*argv && **argv == '+') {
175 setthetime(fmt, *argv, jflag, &ts);
177 } else if (fmt != NULL)
180 if (*argv && **argv == '+') {
186 if (outzone != NULL && setenv("TZ", outzone, 1) != 0)
187 err(1, "setenv(TZ)");
188 lt = localtime(&ts.tv_sec);
190 errx(1, "invalid time");
191 badv = vary_apply(v, lt);
193 fprintf(stderr, "%s: Cannot apply date adjustment\n",
201 printisodate(lt, ts.tv_nsec);
203 if (format == rfc2822_format)
205 * When using RFC 2822 datetime format, don't honor the
208 setlocale(LC_TIME, "C");
211 (void)strftime_ns(buf, sizeof(buf), format, lt, ts.tv_nsec);
216 printdate(const char *buf)
218 (void)printf("%s\n", buf);
225 printisodate(struct tm *lt, long nsec)
227 const struct iso8601_fmt *it;
228 char fmtbuf[64], buf[64], tzbuf[8];
231 for (it = iso8601_fmts; it <= iso8601_selected; it++)
232 strlcat(fmtbuf, it->format_string, sizeof(fmtbuf));
234 (void)strftime_ns(buf, sizeof(buf), fmtbuf, lt, nsec);
236 if (iso8601_selected > iso8601_fmts) {
237 (void)strftime_ns(tzbuf, sizeof(tzbuf), "%z", lt, nsec);
238 memmove(&tzbuf[4], &tzbuf[3], 3);
240 strlcat(buf, tzbuf, sizeof(buf));
246 #define ATOI2(s) ((s) += 2, ((s)[-2] - '0') * 10 + ((s)[-1] - '0'))
249 setthetime(const char *fmt, const char *p, int jflag, struct timespec *ts)
256 lt = localtime(&ts->tv_sec);
258 errx(1, "invalid time");
259 lt->tm_isdst = -1; /* divine correct DST */
262 t = strptime(p, fmt, lt);
264 fprintf(stderr, "Failed conversion of ``%s''"
265 " using format ``%s''\n", p, fmt);
267 } else if (*t != '\0')
268 fprintf(stderr, "Warning: Ignoring %ld extraneous"
269 " characters in date string (%s)\n",
270 (long) strlen(t), t);
272 for (t = p, dot = NULL; *t; ++t) {
275 if (*t == '.' && dot == NULL) {
282 if (dot != NULL) { /* .ss */
283 dot++; /* *dot++ = '\0'; */
284 if (strlen(dot) != 2)
286 lt->tm_sec = ATOI2(dot);
293 /* if p has a ".ss" field then let's pretend it's not there */
294 switch (strlen(p) - ((dot != NULL) ? 3 : 0)) {
296 lt->tm_year = ATOI2(p) * 100 - TM_YEAR_BASE;
301 lt->tm_year += ATOI2(p);
303 lt->tm_year = ATOI2(p);
304 if (lt->tm_year < 69) /* hack for 2000 ;-} */
305 lt->tm_year += 2000 - TM_YEAR_BASE;
307 lt->tm_year += 1900 - TM_YEAR_BASE;
311 lt->tm_mon = ATOI2(p);
314 --lt->tm_mon; /* time struct is 0 - 11 */
317 lt->tm_mday = ATOI2(p);
318 if (lt->tm_mday > 31)
322 lt->tm_hour = ATOI2(p);
323 if (lt->tm_hour > 23)
327 lt->tm_min = ATOI2(p);
336 /* convert broken-down time to GMT clock time */
338 ts->tv_sec = mktime(lt);
339 if (lt->tm_yday == -1)
340 errx(1, "nonexistent time");
344 utx.ut_type = OLD_TIME;
345 memset(utx.ut_id, 0, sizeof(utx.ut_id));
346 (void)gettimeofday(&utx.ut_tv, NULL);
348 if (clock_settime(CLOCK_REALTIME, ts) != 0)
349 err(1, "clock_settime");
350 utx.ut_type = NEW_TIME;
351 (void)gettimeofday(&utx.ut_tv, NULL);
354 if ((p = getlogin()) == NULL)
356 syslog(LOG_AUTH | LOG_NOTICE, "date set by %s", p);
361 * The strftime_ns function is a wrapper around strftime(3), which adds support
362 * for features absent from strftime(3). Currently, the only extra feature is
363 * support for %N, the nanosecond conversion specification.
365 * The functions scans the format string for the non-standard conversion
366 * specifications and replaces them with the date and time values before
367 * passing the format string to strftime(3). The handling of the non-standard
368 * conversion specifications happens before the call to strftime(3) to handle
369 * cases like "%%N" correctly ("%%N" should yield "%N" instead of nanoseconds).
372 strftime_ns(char * __restrict s, size_t maxsize, const char * __restrict format,
373 const struct tm * __restrict t, long nsec)
384 seen_percent = false;
385 if (asprintf(&newformat, "%s", format) < 0)
388 for (tok = newformat; *tok != '\0'; tok++) {
392 * If the previous token was a percent sign,
393 * then there are two percent tokens in a row.
396 seen_percent = false;
402 oldformat = newformat;
404 prefixlen = tok - oldformat - 1;
407 * Construct a new format string from the
408 * prefix (i.e., the part of the old fromat
409 * from its beginning to the currently handled
410 * "%N" conversion specification, the
411 * nanoseconds, and the suffix (i.e., the part
412 * of the old format from the next token to the
415 if (asprintf(&newformat, "%.*s%.9ld%s",
416 (int)prefixlen, prefix, nsec,
421 tok = newformat + prefixlen + 9;
423 seen_percent = false;
426 seen_percent = false;
431 ret = strftime(s, maxsize, newformat, t);
439 warnx("illegal time format");
444 iso8601_usage(const char *badarg)
446 errx(1, "invalid argument '%s' for -I", badarg);
450 multipleformats(void)
452 errx(1, "multiple output formats specified");
458 (void)fprintf(stderr, "%s\n%s\n%s\n",
459 "usage: date [-jnRu] [-I[date|hours|minutes|seconds|ns]] [-f input_fmt]",
461 "[ -z output_zone ] [-r filename|seconds] [-v[+|-]val[y|m|w|d|H|M|S]]",
463 "[[[[[[cc]yy]mm]dd]HH]MM[.SS] | new_date] [+output_fmt]"