* src/dd.c (flags): noatime and nofollow now depend on
[coreutils/bo.git] / src / date.c
blob187956a3115d4434f4e63ca87c89c2739127bea7
1 /* date - print or set the system date and time
2 Copyright (C) 1989-2006 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 2, or (at your option)
7 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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 David MacKenzie <djm@gnu.ai.mit.edu> */
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24 #if HAVE_LANGINFO_CODESET
25 # include <langinfo.h>
26 #endif
28 #include "system.h"
29 #include "argmatch.h"
30 #include "error.h"
31 #include "getdate.h"
32 #include "getline.h"
33 #include "inttostr.h"
34 #include "posixtm.h"
35 #include "quote.h"
36 #include "stat-time.h"
37 #include "fprintftime.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "date"
42 #define AUTHORS "David MacKenzie"
44 int putenv ();
46 static bool show_date (const char *format, struct timespec when);
48 enum Time_spec
50 /* Display only the date. */
51 TIME_SPEC_DATE,
52 /* Display date, hours, minutes, and seconds. */
53 TIME_SPEC_SECONDS,
54 /* Similar, but display nanoseconds. */
55 TIME_SPEC_NS,
57 /* Put these last, since they aren't valid for --rfc-3339. */
59 /* Display date and hour. */
60 TIME_SPEC_HOURS,
61 /* Display date, hours, and minutes. */
62 TIME_SPEC_MINUTES
65 static char const *const time_spec_string[] =
67 /* Put "hours" and "minutes" first, since they aren't valid for
68 --rfc-3339. */
69 "hours", "minutes",
70 "date", "seconds", "ns", NULL
72 static enum Time_spec const time_spec[] =
74 TIME_SPEC_HOURS, TIME_SPEC_MINUTES,
75 TIME_SPEC_DATE, TIME_SPEC_SECONDS, TIME_SPEC_NS
77 ARGMATCH_VERIFY (time_spec_string, time_spec);
79 /* A format suitable for Internet RFC 2822. */
80 static char const rfc_2822_format[] = "%a, %d %b %Y %H:%M:%S %z";
82 /* The name this program was run with, for error messages. */
83 char *program_name;
85 /* For long options that have no equivalent short option, use a
86 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
87 enum
89 RFC_3339_OPTION = CHAR_MAX + 1
92 static char const short_options[] = "d:f:I::r:Rs:u";
94 static struct option const long_options[] =
96 {"date", required_argument, NULL, 'd'},
97 {"file", required_argument, NULL, 'f'},
98 {"iso-8601", optional_argument, NULL, 'I'}, /* Deprecated. */
99 {"reference", required_argument, NULL, 'r'},
100 {"rfc-822", no_argument, NULL, 'R'},
101 {"rfc-2822", no_argument, NULL, 'R'},
102 {"rfc-3339", required_argument, NULL, RFC_3339_OPTION},
103 {"set", required_argument, NULL, 's'},
104 {"uct", no_argument, NULL, 'u'},
105 {"utc", no_argument, NULL, 'u'},
106 {"universal", no_argument, NULL, 'u'},
107 {GETOPT_HELP_OPTION_DECL},
108 {GETOPT_VERSION_OPTION_DECL},
109 {NULL, 0, NULL, 0}
112 #if LOCALTIME_CACHE
113 # define TZSET tzset ()
114 #else
115 # define TZSET /* empty */
116 #endif
118 #ifdef _DATE_FMT
119 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
120 #else
121 # define DATE_FMT_LANGINFO() ""
122 #endif
124 void
125 usage (int status)
127 if (status != EXIT_SUCCESS)
128 fprintf (stderr, _("Try `%s --help' for more information.\n"),
129 program_name);
130 else
132 printf (_("\
133 Usage: %s [OPTION]... [+FORMAT]\n\
134 or: %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\
136 program_name, program_name);
137 fputs (_("\
138 Display the current time in the given FORMAT, or set the system date.\n\
140 -d, --date=STRING display time described by STRING, not `now'\n\
141 -f, --file=DATEFILE like --date once for each line of DATEFILE\n\
142 "), stdout);
143 fputs (_("\
144 -r, --reference=FILE display the last modification time of FILE\n\
145 -R, --rfc-2822 output date and time in RFC 2822 format\n\
146 --rfc-3339=TIMESPEC output date and time in RFC 3339 format.\n\
147 TIMESPEC=`date', `seconds', or `ns' for\n\
148 date and time to the indicated precision.\n\
149 -s, --set=STRING set time described by STRING\n\
150 -u, --utc, --universal print or set Coordinated Universal Time\n\
151 "), stdout);
152 fputs (HELP_OPTION_DESCRIPTION, stdout);
153 fputs (VERSION_OPTION_DESCRIPTION, stdout);
154 fputs (_("\
156 FORMAT controls the output. The only valid option for the second form\n\
157 specifies Coordinated Universal Time. Interpreted sequences are:\n\
159 %% a literal %\n\
160 %a locale's abbreviated weekday name (e.g., Sun)\n\
161 "), stdout);
162 fputs (_("\
163 %A locale's full weekday name (e.g., Sunday)\n\
164 %b locale's abbreviated month name (e.g., Jan)\n\
165 %B locale's full month name (e.g., January)\n\
166 %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)\n\
167 "), stdout);
168 fputs (_("\
169 %C century; like %Y, except omit last two digits (e.g., 21)\n\
170 %d day of month (e.g, 01)\n\
171 %D date; same as %m/%d/%y\n\
172 %e day of month, space padded; same as %_d\n\
173 "), stdout);
174 fputs (_("\
175 %F full date; same as %Y-%m-%d\n\
176 %g last two digits of year of ISO week number (see %G)\n\
177 %G year of ISO week number (see %V); normally useful only with %V\n\
178 "), stdout);
179 fputs (_("\
180 %h same as %b\n\
181 %H hour (00..23)\n\
182 %I hour (01..12)\n\
183 %j day of year (001..366)\n\
184 "), stdout);
185 fputs (_("\
186 %k hour ( 0..23)\n\
187 %l hour ( 1..12)\n\
188 %m month (01..12)\n\
189 %M minute (00..59)\n\
190 "), stdout);
191 fputs (_("\
192 %n a newline\n\
193 %N nanoseconds (000000000..999999999)\n\
194 %p locale's equivalent of either AM or PM; blank if not known\n\
195 %P like %p, but lower case\n\
196 %r locale's 12-hour clock time (e.g., 11:11:04 PM)\n\
197 %R 24-hour hour and minute; same as %H:%M\n\
198 %s seconds since 1970-01-01 00:00:00 UTC\n\
199 "), stdout);
200 fputs (_("\
201 %S second (00..60)\n\
202 %t a tab\n\
203 %T time; same as %H:%M:%S\n\
204 %u day of week (1..7); 1 is Monday\n\
205 "), stdout);
206 fputs (_("\
207 %U week number of year, with Sunday as first day of week (00..53)\n\
208 %V ISO week number, with Monday as first day of week (01..53)\n\
209 %w day of week (0..6); 0 is Sunday\n\
210 %W week number of year, with Monday as first day of week (00..53)\n\
211 "), stdout);
212 fputs (_("\
213 %x locale's date representation (e.g., 12/31/99)\n\
214 %X locale's time representation (e.g., 23:13:48)\n\
215 %y last two digits of year (00..99)\n\
216 %Y year\n\
217 "), stdout);
218 fputs (_("\
219 %z +hhmm numeric timezone (e.g., -0400)\n\
220 %:z +hh:mm numeric timezone (e.g., -04:00)\n\
221 %::z +hh:mm:ss numeric time zone (e.g., -04:00:00)\n\
222 %:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)\n\
223 %Z alphabetic time zone abbreviation (e.g., EDT)\n\
225 By default, date pads numeric fields with zeroes.\n\
226 The following optional flags may follow `%':\n\
228 - (hyphen) do not pad the field\n\
229 _ (underscore) pad with spaces\n\
230 0 (zero) pad with zeros\n\
231 ^ use upper case if possible\n\
232 # use opposite case if possible\n\
233 "), stdout);
234 fputs (_("\
236 After any flags comes an optional field width, as a decimal number;\n\
237 then an optional modifier, which is either\n\
238 E to use the locale's alternate representations if available, or\n\
239 O to use the locale's alternate numeric symbols if available.\n\
240 "), stdout);
241 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
243 exit (status);
246 /* Parse each line in INPUT_FILENAME as with --date and display each
247 resulting time and date. If the file cannot be opened, tell why
248 then exit. Issue a diagnostic for any lines that cannot be parsed.
249 Return true if successful. */
251 static bool
252 batch_convert (const char *input_filename, const char *format)
254 bool ok;
255 FILE *in_stream;
256 char *line;
257 size_t buflen;
258 struct timespec when;
260 if (STREQ (input_filename, "-"))
262 input_filename = _("standard input");
263 in_stream = stdin;
265 else
267 in_stream = fopen (input_filename, "r");
268 if (in_stream == NULL)
270 error (EXIT_FAILURE, errno, "%s", quote (input_filename));
274 line = NULL;
275 buflen = 0;
276 ok = true;
277 while (1)
279 ssize_t line_length = getline (&line, &buflen, in_stream);
280 if (line_length < 0)
282 /* FIXME: detect/handle error here. */
283 break;
286 if (! get_date (&when, line, NULL))
288 if (line[line_length - 1] == '\n')
289 line[line_length - 1] = '\0';
290 error (0, 0, _("invalid date %s"), quote (line));
291 ok = false;
293 else
295 ok &= show_date (format, when);
299 if (fclose (in_stream) == EOF)
300 error (EXIT_FAILURE, errno, "%s", quote (input_filename));
302 free (line);
304 return ok;
308 main (int argc, char **argv)
310 int optc;
311 const char *datestr = NULL;
312 const char *set_datestr = NULL;
313 struct timespec when;
314 bool set_date = false;
315 char const *format = NULL;
316 char *batch_file = NULL;
317 char *reference = NULL;
318 struct stat refstats;
319 bool ok;
320 int option_specified_date;
322 initialize_main (&argc, &argv);
323 program_name = argv[0];
324 setlocale (LC_ALL, "");
325 bindtextdomain (PACKAGE, LOCALEDIR);
326 textdomain (PACKAGE);
328 atexit (close_stdout);
330 while ((optc = getopt_long (argc, argv, short_options, long_options, NULL))
331 != -1)
333 char const *new_format = NULL;
335 switch (optc)
337 case 'd':
338 datestr = optarg;
339 break;
340 case 'f':
341 batch_file = optarg;
342 break;
343 case RFC_3339_OPTION:
345 static char const rfc_3339_format[][32] =
347 "%Y-%m-%d",
348 "%Y-%m-%d %H:%M:%S%:z",
349 "%Y-%m-%d %H:%M:%S.%N%:z"
351 enum Time_spec i =
352 XARGMATCH ("--rfc-3339", optarg,
353 time_spec_string + 2, time_spec + 2);
354 new_format = rfc_3339_format[i];
355 break;
357 case 'I':
359 static char const iso_8601_format[][32] =
361 "%Y-%m-%d",
362 "%Y-%m-%dT%H:%M:%S%z",
363 "%Y-%m-%dT%H:%M:%S,%N%z",
364 "%Y-%m-%dT%H%z",
365 "%Y-%m-%dT%H:%M%z"
367 enum Time_spec i =
368 (optarg
369 ? XARGMATCH ("--iso-8601", optarg, time_spec_string, time_spec)
370 : TIME_SPEC_DATE);
371 new_format = iso_8601_format[i];
372 break;
374 case 'r':
375 reference = optarg;
376 break;
377 case 'R':
378 new_format = rfc_2822_format;
379 break;
380 case 's':
381 set_datestr = optarg;
382 set_date = true;
383 break;
384 case 'u':
385 /* POSIX says that `date -u' is equivalent to setting the TZ
386 environment variable, so this option should do nothing other
387 than setting TZ. */
388 if (putenv ("TZ=UTC0") != 0)
389 xalloc_die ();
390 TZSET;
391 break;
392 case_GETOPT_HELP_CHAR;
393 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
394 default:
395 usage (EXIT_FAILURE);
398 if (new_format)
400 if (format)
401 error (EXIT_FAILURE, 0, _("multiple output formats specified"));
402 format = new_format;
406 option_specified_date = ((datestr ? 1 : 0)
407 + (batch_file ? 1 : 0)
408 + (reference ? 1 : 0));
410 if (option_specified_date > 1)
412 error (0, 0,
413 _("the options to specify dates for printing are mutually exclusive"));
414 usage (EXIT_FAILURE);
417 if (set_date && option_specified_date)
419 error (0, 0,
420 _("the options to print and set the time may not be used together"));
421 usage (EXIT_FAILURE);
424 if (optind < argc)
426 if (optind + 1 < argc)
428 error (0, 0, _("extra operand %s"), quote (argv[optind + 1]));
429 usage (EXIT_FAILURE);
432 if (argv[optind][0] == '+')
434 if (format)
435 error (EXIT_FAILURE, 0, _("multiple output formats specified"));
436 format = argv[optind++] + 1;
438 else if (set_date || option_specified_date)
440 error (0, 0,
441 _("the argument %s lacks a leading `+';\n"
442 "When using an option to specify date(s), any non-option\n"
443 "argument must be a format string beginning with `+'."),
444 quote (argv[optind]));
445 usage (EXIT_FAILURE);
449 if (!format)
451 format = DATE_FMT_LANGINFO ();
452 if (! *format)
454 /* Do not wrap the following literal format string with _(...).
455 For example, suppose LC_ALL is unset, LC_TIME="POSIX",
456 and LANG="ko_KR". In that case, POSIX says that LC_TIME
457 determines the format and contents of date and time strings
458 written by date, which means "date" must generate output
459 using the POSIX locale; but adding _() would cause "date"
460 to use a Korean translation of the format. */
461 format = "%a %b %e %H:%M:%S %Z %Y";
465 if (batch_file != NULL)
466 ok = batch_convert (batch_file, format);
467 else
469 bool valid_date = true;
470 ok = true;
472 if (!option_specified_date && !set_date)
474 if (optind < argc)
476 /* Prepare to set system clock to the specified date/time
477 given in the POSIX-format. */
478 set_date = true;
479 datestr = argv[optind];
480 valid_date = posixtime (&when.tv_sec,
481 datestr,
482 (PDS_TRAILING_YEAR
483 | PDS_CENTURY | PDS_SECONDS));
484 when.tv_nsec = 0; /* FIXME: posixtime should set this. */
486 else
488 /* Prepare to print the current date/time. */
489 gettime (&when);
492 else
494 /* (option_specified_date || set_date) */
495 if (reference != NULL)
497 if (stat (reference, &refstats) != 0)
498 error (EXIT_FAILURE, errno, "%s", reference);
499 when = get_stat_mtime (&refstats);
501 else
503 if (set_datestr)
504 datestr = set_datestr;
505 valid_date = get_date (&when, datestr, NULL);
509 if (! valid_date)
510 error (EXIT_FAILURE, 0, _("invalid date %s"), quote (datestr));
512 if (set_date)
514 /* Set the system clock to the specified date, then regardless of
515 the success of that operation, format and print that date. */
516 if (settime (&when) != 0)
518 error (0, errno, _("cannot set date"));
519 ok = false;
523 ok &= show_date (format, when);
526 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
529 /* Display the date and/or time in WHEN according to the format specified
530 in FORMAT, followed by a newline. Return true if successful. */
532 static bool
533 show_date (const char *format, struct timespec when)
535 struct tm *tm;
537 tm = localtime (&when.tv_sec);
538 if (! tm)
540 char buf[INT_BUFSIZE_BOUND (intmax_t)];
541 error (0, 0, _("time %s is out of range"),
542 (TYPE_SIGNED (time_t)
543 ? imaxtostr (when.tv_sec, buf)
544 : umaxtostr (when.tv_sec, buf)));
545 return false;
548 if (format == rfc_2822_format)
549 setlocale (LC_TIME, "C");
550 fprintftime (stdout, format, tm, 0, when.tv_nsec);
551 fputc ('\n', stdout);
552 if (format == rfc_2822_format)
553 setlocale (LC_TIME, "");
555 return true;