tests: fix false failure on new ls test
[coreutils.git] / src / date.c
blobddb011e65892436b2e41092754bcbf40a2164382
1 /* date - print or set the system date and time
2 Copyright (C) 1989-2016 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 <http://www.gnu.org/licenses/>.
17 David MacKenzie <djm@gnu.ai.mit.edu> */
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #if HAVE_LANGINFO_CODESET
24 # include <langinfo.h>
25 #endif
27 #include "system.h"
28 #include "argmatch.h"
29 #include "die.h"
30 #include "error.h"
31 #include "parse-datetime.h"
32 #include "posixtm.h"
33 #include "quote.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 (const char *, struct timespec, timezone_t);
44 enum Time_spec
46 /* Display only the date. */
47 TIME_SPEC_DATE,
48 /* Display date, hours, minutes, and seconds. */
49 TIME_SPEC_SECONDS,
50 /* Similar, but display nanoseconds. */
51 TIME_SPEC_NS,
53 /* Put these last, since they aren't valid for --rfc-3339. */
55 /* Display date and hour. */
56 TIME_SPEC_HOURS,
57 /* Display date, hours, and minutes. */
58 TIME_SPEC_MINUTES
61 static char const *const time_spec_string[] =
63 /* Put "hours" and "minutes" first, since they aren't valid for
64 --rfc-3339. */
65 "hours", "minutes",
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 RFC 2822. */
76 static char const rfc_2822_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. */
80 enum
82 RFC_3339_OPTION = CHAR_MAX + 1,
83 DEBUG_DATE_PARSING
86 static char const short_options[] = "d:f:I::r:Rs:u";
88 static struct option const long_options[] =
90 {"date", required_argument, NULL, 'd'},
91 {"debug", no_argument, NULL, DEBUG_DATE_PARSING},
92 {"file", required_argument, NULL, 'f'},
93 {"iso-8601", optional_argument, NULL, 'I'},
94 {"reference", required_argument, NULL, 'r'},
95 {"rfc-822", no_argument, NULL, 'R'},
96 {"rfc-2822", no_argument, NULL, 'R'},
97 {"rfc-3339", required_argument, NULL, RFC_3339_OPTION},
98 {"set", required_argument, NULL, 's'},
99 {"uct", no_argument, NULL, 'u'},
100 {"utc", no_argument, NULL, 'u'},
101 {"universal", no_argument, NULL, 'u'},
102 {GETOPT_HELP_OPTION_DECL},
103 {GETOPT_VERSION_OPTION_DECL},
104 {NULL, 0, NULL, 0}
107 /* flags for parse_datetime2 */
108 static unsigned int parse_datetime_flags;
110 #if LOCALTIME_CACHE
111 # define TZSET tzset ()
112 #else
113 # define TZSET /* empty */
114 #endif
116 #ifdef _DATE_FMT
117 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
118 #else
119 # define DATE_FMT_LANGINFO() ""
120 #endif
122 void
123 usage (int status)
125 if (status != EXIT_SUCCESS)
126 emit_try_help ();
127 else
129 printf (_("\
130 Usage: %s [OPTION]... [+FORMAT]\n\
131 or: %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\
133 program_name, program_name);
134 fputs (_("\
135 Display the current time in the given FORMAT, or set the system date.\n\
136 "), stdout);
138 emit_mandatory_arg_note ();
140 fputs (_("\
141 -d, --date=STRING display time described by STRING, not 'now'\n\
142 "), stdout);
143 fputs (_("\
144 --debug annotate the parsed date,\n\
145 and warn about questionable usage to stderr\n\
146 "), stdout);
147 fputs (_("\
148 -f, --file=DATEFILE like --date; once for each line of DATEFILE\n\
149 "), stdout);
150 fputs (_("\
151 -I[FMT], --iso-8601[=FMT] output date/time in ISO 8601 format.\n\
152 FMT='date' for date only (the default),\n\
153 'hours', 'minutes', 'seconds', or 'ns'\n\
154 for date and time to the indicated precision.\n\
155 Example: 2006-08-14T02:34:56-06:00\n\
156 "), stdout);
157 fputs (_("\
158 -R, --rfc-2822 output date and time in RFC 2822 format.\n\
159 Example: Mon, 14 Aug 2006 02:34:56 -0600\n\
160 "), stdout);
161 fputs (_("\
162 --rfc-3339=FMT output date/time in RFC 3339 format.\n\
163 FMT='date', 'seconds', or 'ns'\n\
164 for date and time to the indicated precision.\n\
165 Example: 2006-08-14 02:34:56-06:00\n\
166 "), stdout);
167 fputs (_("\
168 -r, --reference=FILE display the last modification time of FILE\n\
169 "), stdout);
170 fputs (_("\
171 -s, --set=STRING set time described by STRING\n\
172 -u, --utc, --universal print or set Coordinated Universal Time (UTC)\n\
173 "), stdout);
174 fputs (HELP_OPTION_DESCRIPTION, stdout);
175 fputs (VERSION_OPTION_DESCRIPTION, stdout);
176 fputs (_("\
178 FORMAT controls the output. Interpreted sequences are:\n\
180 %% a literal %\n\
181 %a locale's abbreviated weekday name (e.g., Sun)\n\
182 "), stdout);
183 fputs (_("\
184 %A locale's full weekday name (e.g., Sunday)\n\
185 %b locale's abbreviated month name (e.g., Jan)\n\
186 %B locale's full month name (e.g., January)\n\
187 %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)\n\
188 "), stdout);
189 fputs (_("\
190 %C century; like %Y, except omit last two digits (e.g., 20)\n\
191 %d day of month (e.g., 01)\n\
192 %D date; same as %m/%d/%y\n\
193 %e day of month, space padded; same as %_d\n\
194 "), stdout);
195 fputs (_("\
196 %F full date; same as %Y-%m-%d\n\
197 %g last two digits of year of ISO week number (see %G)\n\
198 %G year of ISO week number (see %V); normally useful only with %V\n\
199 "), stdout);
200 fputs (_("\
201 %h same as %b\n\
202 %H hour (00..23)\n\
203 %I hour (01..12)\n\
204 %j day of year (001..366)\n\
205 "), stdout);
206 fputs (_("\
207 %k hour, space padded ( 0..23); same as %_H\n\
208 %l hour, space padded ( 1..12); same as %_I\n\
209 %m month (01..12)\n\
210 %M minute (00..59)\n\
211 "), stdout);
212 fputs (_("\
213 %n a newline\n\
214 %N nanoseconds (000000000..999999999)\n\
215 %p locale's equivalent of either AM or PM; blank if not known\n\
216 %P like %p, but lower case\n\
217 %q quarter of year (1..4)\n\
218 %r locale's 12-hour clock time (e.g., 11:11:04 PM)\n\
219 %R 24-hour hour and minute; same as %H:%M\n\
220 %s seconds since 1970-01-01 00:00:00 UTC\n\
221 "), stdout);
222 fputs (_("\
223 %S second (00..60)\n\
224 %t a tab\n\
225 %T time; same as %H:%M:%S\n\
226 %u day of week (1..7); 1 is Monday\n\
227 "), stdout);
228 fputs (_("\
229 %U week number of year, with Sunday as first day of week (00..53)\n\
230 %V ISO week number, with Monday as first day of week (01..53)\n\
231 %w day of week (0..6); 0 is Sunday\n\
232 %W week number of year, with Monday as first day of week (00..53)\n\
233 "), stdout);
234 fputs (_("\
235 %x locale's date representation (e.g., 12/31/99)\n\
236 %X locale's time representation (e.g., 23:13:48)\n\
237 %y last two digits of year (00..99)\n\
238 %Y year\n\
239 "), stdout);
240 fputs (_("\
241 %z +hhmm numeric time zone (e.g., -0400)\n\
242 %:z +hh:mm numeric time zone (e.g., -04:00)\n\
243 %::z +hh:mm:ss numeric time zone (e.g., -04:00:00)\n\
244 %:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)\n\
245 %Z alphabetic time zone abbreviation (e.g., EDT)\n\
247 By default, date pads numeric fields with zeroes.\n\
248 "), stdout);
249 fputs (_("\
250 The following optional flags may follow '%':\n\
252 - (hyphen) do not pad the field\n\
253 _ (underscore) pad with spaces\n\
254 0 (zero) pad with zeros\n\
255 ^ use upper case if possible\n\
256 # use opposite case if possible\n\
257 "), stdout);
258 fputs (_("\
260 After any flags comes an optional field width, as a decimal number;\n\
261 then an optional modifier, which is either\n\
262 E to use the locale's alternate representations if available, or\n\
263 O to use the locale's alternate numeric symbols if available.\n\
264 "), stdout);
265 fputs (_("\
267 Examples:\n\
268 Convert seconds since the epoch (1970-01-01 UTC) to a date\n\
269 $ date --date='@2147483647'\n\
271 Show the time on the west coast of the US (use tzselect(1) to find TZ)\n\
272 $ TZ='America/Los_Angeles' date\n\
274 Show the local time for 9AM next Friday on the west coast of the US\n\
275 $ date --date='TZ=\"America/Los_Angeles\" 09:00 next Fri'\n\
276 "), stdout);
277 emit_ancillary_info (PROGRAM_NAME);
279 exit (status);
282 /* Parse each line in INPUT_FILENAME as with --date and display each
283 resulting time and date. If the file cannot be opened, tell why
284 then exit. Issue a diagnostic for any lines that cannot be parsed.
285 Return true if successful. */
287 static bool
288 batch_convert (const char *input_filename, const char *format, timezone_t tz)
290 bool ok;
291 FILE *in_stream;
292 char *line;
293 size_t buflen;
294 struct timespec when;
296 if (STREQ (input_filename, "-"))
298 input_filename = _("standard input");
299 in_stream = stdin;
301 else
303 in_stream = fopen (input_filename, "r");
304 if (in_stream == NULL)
306 die (EXIT_FAILURE, errno, "%s", quotef (input_filename));
310 line = NULL;
311 buflen = 0;
312 ok = true;
313 while (1)
315 ssize_t line_length = getline (&line, &buflen, in_stream);
316 if (line_length < 0)
318 /* FIXME: detect/handle error here. */
319 break;
322 if (! parse_datetime2 (&when, line, NULL, parse_datetime_flags))
324 if (line[line_length - 1] == '\n')
325 line[line_length - 1] = '\0';
326 error (0, 0, _("invalid date %s"), quote (line));
327 ok = false;
329 else
331 ok &= show_date (format, when, tz);
335 if (fclose (in_stream) == EOF)
336 die (EXIT_FAILURE, errno, "%s", quotef (input_filename));
338 free (line);
340 return ok;
344 main (int argc, char **argv)
346 int optc;
347 const char *datestr = NULL;
348 const char *set_datestr = NULL;
349 struct timespec when;
350 bool set_date = false;
351 char const *format = NULL;
352 char *batch_file = NULL;
353 char *reference = NULL;
354 struct stat refstats;
355 bool ok;
356 int option_specified_date;
358 initialize_main (&argc, &argv);
359 set_program_name (argv[0]);
360 setlocale (LC_ALL, "");
361 bindtextdomain (PACKAGE, LOCALEDIR);
362 textdomain (PACKAGE);
364 atexit (close_stdout);
366 while ((optc = getopt_long (argc, argv, short_options, long_options, NULL))
367 != -1)
369 char const *new_format = NULL;
371 switch (optc)
373 case 'd':
374 datestr = optarg;
375 break;
376 case DEBUG_DATE_PARSING:
377 parse_datetime_flags |= PARSE_DATETIME_DEBUG;
378 break;
379 case 'f':
380 batch_file = optarg;
381 break;
382 case RFC_3339_OPTION:
384 static char const rfc_3339_format[][32] =
386 "%Y-%m-%d",
387 "%Y-%m-%d %H:%M:%S%:z",
388 "%Y-%m-%d %H:%M:%S.%N%:z"
390 enum Time_spec i =
391 XARGMATCH ("--rfc-3339", optarg,
392 time_spec_string + 2, time_spec + 2);
393 new_format = rfc_3339_format[i];
394 break;
396 case 'I':
398 static char const iso_8601_format[][32] =
400 "%Y-%m-%d",
401 "%Y-%m-%dT%H:%M:%S%:z",
402 "%Y-%m-%dT%H:%M:%S,%N%:z",
403 "%Y-%m-%dT%H%:z",
404 "%Y-%m-%dT%H:%M%:z"
406 enum Time_spec i =
407 (optarg
408 ? XARGMATCH ("--iso-8601", optarg, time_spec_string, time_spec)
409 : TIME_SPEC_DATE);
410 new_format = iso_8601_format[i];
411 break;
413 case 'r':
414 reference = optarg;
415 break;
416 case 'R':
417 new_format = rfc_2822_format;
418 break;
419 case 's':
420 set_datestr = optarg;
421 set_date = true;
422 break;
423 case 'u':
424 /* POSIX says that 'date -u' is equivalent to setting the TZ
425 environment variable, so this option should do nothing other
426 than setting TZ. */
427 if (putenv (bad_cast ("TZ=UTC0")) != 0)
428 xalloc_die ();
429 TZSET;
430 break;
431 case_GETOPT_HELP_CHAR;
432 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
433 default:
434 usage (EXIT_FAILURE);
437 if (new_format)
439 if (format)
440 die (EXIT_FAILURE, 0, _("multiple output formats specified"));
441 format = new_format;
445 option_specified_date = ((datestr ? 1 : 0)
446 + (batch_file ? 1 : 0)
447 + (reference ? 1 : 0));
449 if (option_specified_date > 1)
451 error (0, 0,
452 _("the options to specify dates for printing are mutually exclusive"));
453 usage (EXIT_FAILURE);
456 if (set_date && option_specified_date)
458 error (0, 0,
459 _("the options to print and set the time may not be used together"));
460 usage (EXIT_FAILURE);
463 if (optind < argc)
465 if (optind + 1 < argc)
467 error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
468 usage (EXIT_FAILURE);
471 if (argv[optind][0] == '+')
473 if (format)
474 die (EXIT_FAILURE, 0, _("multiple output formats specified"));
475 format = argv[optind++] + 1;
477 else if (set_date || option_specified_date)
479 error (0, 0,
480 _("the argument %s lacks a leading '+';\n"
481 "when using an option to specify date(s), any non-option\n"
482 "argument must be a format string beginning with '+'"),
483 quote (argv[optind]));
484 usage (EXIT_FAILURE);
488 if (!format)
490 format = DATE_FMT_LANGINFO ();
491 if (! *format)
493 /* Do not wrap the following literal format string with _(...).
494 For example, suppose LC_ALL is unset, LC_TIME=POSIX,
495 and LANG="ko_KR". In that case, POSIX says that LC_TIME
496 determines the format and contents of date and time strings
497 written by date, which means "date" must generate output
498 using the POSIX locale; but adding _() would cause "date"
499 to use a Korean translation of the format. */
500 format = "%a %b %e %H:%M:%S %Z %Y";
504 timezone_t tz = tzalloc (getenv ("TZ"));
506 if (batch_file != NULL)
507 ok = batch_convert (batch_file, format, tz);
508 else
510 bool valid_date = true;
511 ok = true;
513 if (!option_specified_date && !set_date)
515 if (optind < argc)
517 /* Prepare to set system clock to the specified date/time
518 given in the POSIX-format. */
519 set_date = true;
520 datestr = argv[optind];
521 valid_date = posixtime (&when.tv_sec,
522 datestr,
523 (PDS_TRAILING_YEAR
524 | PDS_CENTURY | PDS_SECONDS));
525 when.tv_nsec = 0; /* FIXME: posixtime should set this. */
527 else
529 /* Prepare to print the current date/time. */
530 gettime (&when);
533 else
535 /* (option_specified_date || set_date) */
536 if (reference != NULL)
538 if (stat (reference, &refstats) != 0)
539 die (EXIT_FAILURE, errno, "%s", quotef (reference));
540 when = get_stat_mtime (&refstats);
542 else
544 if (set_datestr)
545 datestr = set_datestr;
546 valid_date = parse_datetime2 (&when, datestr, NULL,
547 parse_datetime_flags);
551 if (! valid_date)
552 die (EXIT_FAILURE, 0, _("invalid date %s"), quote (datestr));
554 if (set_date)
556 /* Set the system clock to the specified date, then regardless of
557 the success of that operation, format and print that date. */
558 if (settime (&when) != 0)
560 error (0, errno, _("cannot set date"));
561 ok = false;
565 ok &= show_date (format, when, tz);
568 IF_LINT (tzfree (tz));
570 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
573 /* Display the date and/or time in WHEN according to the format specified
574 in FORMAT, followed by a newline. Return true if successful. */
576 static bool
577 show_date (const char *format, struct timespec when, timezone_t tz)
579 struct tm tm;
581 if (localtime_rz (tz, &when.tv_sec, &tm))
583 if (format == rfc_2822_format)
584 setlocale (LC_TIME, "C");
585 fprintftime (stdout, format, &tm, tz, when.tv_nsec);
586 if (format == rfc_2822_format)
587 setlocale (LC_TIME, "");
588 fputc ('\n', stdout);
589 return true;
591 else
593 char buf[INT_BUFSIZE_BOUND (intmax_t)];
594 error (0, 0, _("time %s is out of range"),
595 quote (timetostr (when.tv_sec, buf)));
596 return false;