1 /* date - print or set the system date and time
2 Copyright (C) 1989-2022 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>.
17 David MacKenzie <djm@gnu.ai.mit.edu> */
22 #include <sys/types.h>
23 #if HAVE_LANGINFO_CODESET
24 # include <langinfo.h>
31 #include "parse-datetime.h"
34 #include "stat-time.h"
35 #include "fprintftime.h"
37 /* The official name of this program (e.g., no 'g' prefix). */
38 #define PROGRAM_NAME "date"
40 #define AUTHORS proper_name ("David MacKenzie")
42 static bool show_date (char const *, struct timespec
, timezone_t
);
46 /* Display only the date. */
48 /* Display date, hours, minutes, and seconds. */
50 /* Similar, but display nanoseconds. */
53 /* Put these last, since they aren't valid for --rfc-3339. */
55 /* Display date and hour. */
57 /* Display date, hours, and minutes. */
61 static char const *const time_spec_string
[] =
63 /* Put "hours" and "minutes" first, since they aren't valid for
66 "date", "seconds", "ns", NULL
68 static enum Time_spec
const time_spec
[] =
70 TIME_SPEC_HOURS
, TIME_SPEC_MINUTES
,
71 TIME_SPEC_DATE
, TIME_SPEC_SECONDS
, TIME_SPEC_NS
73 ARGMATCH_VERIFY (time_spec_string
, time_spec
);
75 /* A format suitable for Internet RFCs 5322, 2822, and 822. */
76 static char const rfc_email_format
[] = "%a, %d %b %Y %H:%M:%S %z";
78 /* For long options that have no equivalent short option, use a
79 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
82 DEBUG_DATE_PARSING_OPTION
= CHAR_MAX
+ 1,
87 static char const short_options
[] = "d:f:I::r:Rs:u";
89 static struct option
const long_options
[] =
91 {"date", required_argument
, NULL
, 'd'},
92 {"debug", no_argument
, NULL
, DEBUG_DATE_PARSING_OPTION
},
93 {"file", required_argument
, NULL
, 'f'},
94 {"iso-8601", optional_argument
, NULL
, 'I'},
95 {"reference", required_argument
, NULL
, 'r'},
96 {"resolution", no_argument
, NULL
, RESOLUTION_OPTION
},
97 {"rfc-email", no_argument
, NULL
, 'R'},
98 {"rfc-822", no_argument
, NULL
, 'R'},
99 {"rfc-2822", no_argument
, NULL
, 'R'},
100 {"rfc-3339", required_argument
, NULL
, RFC_3339_OPTION
},
101 {"set", required_argument
, NULL
, 's'},
102 {"uct", no_argument
, NULL
, 'u'},
103 {"utc", no_argument
, NULL
, 'u'},
104 {"universal", no_argument
, NULL
, 'u'},
105 {GETOPT_HELP_OPTION_DECL
},
106 {GETOPT_VERSION_OPTION_DECL
},
110 /* flags for parse_datetime2 */
111 static unsigned int parse_datetime_flags
;
114 # define TZSET tzset ()
116 # define TZSET /* empty */
120 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
122 # define DATE_FMT_LANGINFO() ""
128 if (status
!= EXIT_SUCCESS
)
133 Usage: %s [OPTION]... [+FORMAT]\n\
134 or: %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\
136 program_name
, program_name
);
138 Display date and time in the given FORMAT.\n\
139 With -s, or with [MMDDhhmm[[CC]YY][.ss]], set the date and time.\n\
142 emit_mandatory_arg_note ();
145 -d, --date=STRING display time described by STRING, not 'now'\n\
148 --debug annotate the parsed date,\n\
149 and warn about questionable usage to stderr\n\
152 -f, --file=DATEFILE like --date; once for each line of DATEFILE\n\
155 -I[FMT], --iso-8601[=FMT] output date/time in ISO 8601 format.\n\
156 FMT='date' for date only (the default),\n\
157 'hours', 'minutes', 'seconds', or 'ns'\n\
158 for date and time to the indicated precision.\n\
159 Example: 2006-08-14T02:34:56-06:00\n\
162 --resolution output the available resolution of timestamps\n\
163 Example: 0.000000001\n\
166 -R, --rfc-email output date and time in RFC 5322 format.\n\
167 Example: Mon, 14 Aug 2006 02:34:56 -0600\n\
170 --rfc-3339=FMT output date/time in RFC 3339 format.\n\
171 FMT='date', 'seconds', or 'ns'\n\
172 for date and time to the indicated precision.\n\
173 Example: 2006-08-14 02:34:56-06:00\n\
176 -r, --reference=FILE display the last modification time of FILE\n\
179 -s, --set=STRING set time described by STRING\n\
180 -u, --utc, --universal print or set Coordinated Universal Time (UTC)\n\
182 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
183 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
186 FORMAT controls the output. Interpreted sequences are:\n\
189 %a locale's abbreviated weekday name (e.g., Sun)\n\
192 %A locale's full weekday name (e.g., Sunday)\n\
193 %b locale's abbreviated month name (e.g., Jan)\n\
194 %B locale's full month name (e.g., January)\n\
195 %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)\n\
198 %C century; like %Y, except omit last two digits (e.g., 20)\n\
199 %d day of month (e.g., 01)\n\
200 %D date; same as %m/%d/%y\n\
201 %e day of month, space padded; same as %_d\n\
204 %F full date; like %+4Y-%m-%d\n\
205 %g last two digits of year of ISO week number (see %G)\n\
206 %G year of ISO week number (see %V); normally useful only with %V\n\
212 %j day of year (001..366)\n\
215 %k hour, space padded ( 0..23); same as %_H\n\
216 %l hour, space padded ( 1..12); same as %_I\n\
218 %M minute (00..59)\n\
222 %N nanoseconds (000000000..999999999)\n\
223 %p locale's equivalent of either AM or PM; blank if not known\n\
224 %P like %p, but lower case\n\
225 %q quarter of year (1..4)\n\
226 %r locale's 12-hour clock time (e.g., 11:11:04 PM)\n\
227 %R 24-hour hour and minute; same as %H:%M\n\
228 %s seconds since the Epoch (1970-01-01 00:00 UTC)\n\
231 %S second (00..60)\n\
233 %T time; same as %H:%M:%S\n\
234 %u day of week (1..7); 1 is Monday\n\
237 %U week number of year, with Sunday as first day of week (00..53)\n\
238 %V ISO week number, with Monday as first day of week (01..53)\n\
239 %w day of week (0..6); 0 is Sunday\n\
240 %W week number of year, with Monday as first day of week (00..53)\n\
243 %x locale's date representation (e.g., 12/31/99)\n\
244 %X locale's time representation (e.g., 23:13:48)\n\
245 %y last two digits of year (00..99)\n\
249 %z +hhmm numeric time zone (e.g., -0400)\n\
250 %:z +hh:mm numeric time zone (e.g., -04:00)\n\
251 %::z +hh:mm:ss numeric time zone (e.g., -04:00:00)\n\
252 %:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)\n\
253 %Z alphabetic time zone abbreviation (e.g., EDT)\n\
255 By default, date pads numeric fields with zeroes.\n\
258 The following optional flags may follow '%':\n\
260 - (hyphen) do not pad the field\n\
261 _ (underscore) pad with spaces\n\
262 0 (zero) pad with zeros\n\
263 + pad with zeros, and put '+' before future years with >4 digits\n\
264 ^ use upper case if possible\n\
265 # use opposite case if possible\n\
269 After any flags comes an optional field width, as a decimal number;\n\
270 then an optional modifier, which is either\n\
271 E to use the locale's alternate representations if available, or\n\
272 O to use the locale's alternate numeric symbols if available.\n\
277 Convert seconds since the Epoch (1970-01-01 UTC) to a date\n\
278 $ date --date='@2147483647'\n\
280 Show the time on the west coast of the US (use tzselect(1) to find TZ)\n\
281 $ TZ='America/Los_Angeles' date\n\
283 Show the local time for 9AM next Friday on the west coast of the US\n\
284 $ date --date='TZ=\"America/Los_Angeles\" 09:00 next Fri'\n\
286 emit_ancillary_info (PROGRAM_NAME
);
291 /* Yield the number of decimal digits needed to output a time with the
292 nanosecond resolution RES, without losing information. */
295 res_width (long int res
)
298 for (long long int r
= 1; (r
*= 10) <= res
; )
303 /* Return a newly allocated copy of FORMAT with each "%-N" adjusted to
304 be "%9N", "%6N", or whatever other resolution is appropriate for
305 the current platform. If no "%-N" appears, return NULL. */
308 adjust_resolution (char const *format
)
312 for (char const *f
= format
; *f
; f
++)
315 if (f
[1] == '-' && f
[2] == 'N')
318 copy
= xstrdup (format
);
319 copy
[f
+ 1 - format
] = '0' + res_width (gettime_res ());
329 /* Parse each line in INPUT_FILENAME as with --date and display each
330 resulting time and date. If the file cannot be opened, tell why
331 then exit. Issue a diagnostic for any lines that cannot be parsed.
332 Return true if successful. */
335 batch_convert (char const *input_filename
, char const *format
,
336 timezone_t tz
, char const *tzstring
)
342 struct timespec when
;
344 if (STREQ (input_filename
, "-"))
346 input_filename
= _("standard input");
351 in_stream
= fopen (input_filename
, "r");
352 if (in_stream
== NULL
)
354 die (EXIT_FAILURE
, errno
, "%s", quotef (input_filename
));
363 ssize_t line_length
= getline (&line
, &buflen
, in_stream
);
366 /* FIXME: detect/handle error here. */
370 if (! parse_datetime2 (&when
, line
, NULL
,
371 parse_datetime_flags
, tz
, tzstring
))
373 if (line
[line_length
- 1] == '\n')
374 line
[line_length
- 1] = '\0';
375 error (0, 0, _("invalid date %s"), quote (line
));
380 ok
&= show_date (format
, when
, tz
);
384 if (fclose (in_stream
) == EOF
)
385 die (EXIT_FAILURE
, errno
, "%s", quotef (input_filename
));
393 main (int argc
, char **argv
)
396 char const *datestr
= NULL
;
397 char const *set_datestr
= NULL
;
398 struct timespec when
;
399 bool set_date
= false;
400 char const *format
= NULL
;
401 bool get_resolution
= false;
402 char *batch_file
= NULL
;
403 char *reference
= NULL
;
404 struct stat refstats
;
407 initialize_main (&argc
, &argv
);
408 set_program_name (argv
[0]);
409 setlocale (LC_ALL
, "");
410 bindtextdomain (PACKAGE
, LOCALEDIR
);
411 textdomain (PACKAGE
);
413 atexit (close_stdout
);
415 while ((optc
= getopt_long (argc
, argv
, short_options
, long_options
, NULL
))
418 char const *new_format
= NULL
;
425 case DEBUG_DATE_PARSING_OPTION
:
426 parse_datetime_flags
|= PARSE_DATETIME_DEBUG
;
431 case RESOLUTION_OPTION
:
432 get_resolution
= true;
434 case RFC_3339_OPTION
:
436 static char const rfc_3339_format
[][32] =
439 "%Y-%m-%d %H:%M:%S%:z",
440 "%Y-%m-%d %H:%M:%S.%N%:z"
443 XARGMATCH ("--rfc-3339", optarg
,
444 time_spec_string
+ 2, time_spec
+ 2);
445 new_format
= rfc_3339_format
[i
];
450 static char const iso_8601_format
[][32] =
453 "%Y-%m-%dT%H:%M:%S%:z",
454 "%Y-%m-%dT%H:%M:%S,%N%:z",
460 ? XARGMATCH ("--iso-8601", optarg
, time_spec_string
, time_spec
)
462 new_format
= iso_8601_format
[i
];
469 new_format
= rfc_email_format
;
472 set_datestr
= optarg
;
476 /* POSIX says that 'date -u' is equivalent to setting the TZ
477 environment variable, so this option should do nothing other
479 if (putenv (bad_cast ("TZ=UTC0")) != 0)
483 case_GETOPT_HELP_CHAR
;
484 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
486 usage (EXIT_FAILURE
);
492 die (EXIT_FAILURE
, 0, _("multiple output formats specified"));
497 int option_specified_date
= (!!datestr
+ !!batch_file
+ !!reference
500 if (option_specified_date
> 1)
503 _("the options to specify dates for printing are mutually exclusive"));
504 usage (EXIT_FAILURE
);
507 if (set_date
&& option_specified_date
)
510 _("the options to print and set the time may not be used together"));
511 usage (EXIT_FAILURE
);
516 if (optind
+ 1 < argc
)
518 error (0, 0, _("extra operand %s"), quote (argv
[optind
+ 1]));
519 usage (EXIT_FAILURE
);
522 if (argv
[optind
][0] == '+')
525 die (EXIT_FAILURE
, 0, _("multiple output formats specified"));
526 format
= argv
[optind
++] + 1;
528 else if (set_date
|| option_specified_date
)
531 _("the argument %s lacks a leading '+';\n"
532 "when using an option to specify date(s), any non-option\n"
533 "argument must be a format string beginning with '+'"),
534 quote (argv
[optind
]));
535 usage (EXIT_FAILURE
);
545 format
= DATE_FMT_LANGINFO ();
547 /* Do not wrap the following literal format string with _(...).
548 For example, suppose LC_ALL is unset, LC_TIME=POSIX,
549 and LANG="ko_KR". In that case, POSIX says that LC_TIME
550 determines the format and contents of date and time strings
551 written by date, which means "date" must generate output
552 using the POSIX locale; but adding _() would cause "date"
553 to use a Korean translation of the format. */
555 format
= "%a %b %e %H:%M:%S %Z %Y";
559 char *format_copy
= adjust_resolution (format
);
560 char const *format_res
= format_copy
? format_copy
: format
;
561 char const *tzstring
= getenv ("TZ");
562 timezone_t tz
= tzalloc (tzstring
);
564 if (batch_file
!= NULL
)
565 ok
= batch_convert (batch_file
, format_res
, tz
, tzstring
);
568 bool valid_date
= true;
571 if (!option_specified_date
&& !set_date
)
575 /* Prepare to set system clock to the specified date/time
576 given in the POSIX-format. */
578 datestr
= argv
[optind
];
579 valid_date
= posixtime (&when
.tv_sec
,
582 | PDS_CENTURY
| PDS_SECONDS
));
583 when
.tv_nsec
= 0; /* FIXME: posixtime should set this. */
587 /* Prepare to print the current date/time. */
593 /* (option_specified_date || set_date) */
594 if (reference
!= NULL
)
596 if (stat (reference
, &refstats
) != 0)
597 die (EXIT_FAILURE
, errno
, "%s", quotef (reference
));
598 when
= get_stat_mtime (&refstats
);
600 else if (get_resolution
)
602 long int res
= gettime_res ();
603 when
.tv_sec
= res
/ TIMESPEC_HZ
;
604 when
.tv_nsec
= res
% TIMESPEC_HZ
;
609 datestr
= set_datestr
;
610 valid_date
= parse_datetime2 (&when
, datestr
, NULL
,
611 parse_datetime_flags
,
617 die (EXIT_FAILURE
, 0, _("invalid date %s"), quote (datestr
));
621 /* Set the system clock to the specified date, then regardless of
622 the success of that operation, format and print that date. */
623 if (settime (&when
) != 0)
625 error (0, errno
, _("cannot set date"));
630 ok
&= show_date (format_res
, when
, tz
);
633 main_exit (ok
? EXIT_SUCCESS
: EXIT_FAILURE
);
636 /* Display the date and/or time in WHEN according to the format specified
637 in FORMAT, followed by a newline. Return true if successful. */
640 show_date (char const *format
, struct timespec when
, timezone_t tz
)
644 if (parse_datetime_flags
& PARSE_DATETIME_DEBUG
)
645 error (0, 0, _("output format: %s"), quote (format
));
647 if (localtime_rz (tz
, &when
.tv_sec
, &tm
))
649 if (format
== rfc_email_format
)
650 setlocale (LC_TIME
, "C");
651 fprintftime (stdout
, format
, &tm
, tz
, when
.tv_nsec
);
652 if (format
== rfc_email_format
)
653 setlocale (LC_TIME
, "");
654 fputc ('\n', stdout
);
659 char buf
[INT_BUFSIZE_BOUND (intmax_t)];
660 error (0, 0, _("time %s is out of range"),
661 quote (timetostr (when
.tv_sec
, buf
)));