(__restrict): Define to `restrict' or to nothing.
[coreutils.git] / src / date.c
blob37295c70dba0bc63070bed21a4dbb2dda004b58a
1 /* date - print or set the system date and time
2 Copyright (C) 1989-2002 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 "closeout.h"
31 #include "error.h"
32 #include "getdate.h"
33 #include "getline.h"
34 #include "posixtm.h"
35 #include "posixver.h"
36 #include "strftime.h"
37 #include "timespec.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 void show_date (const char *format, struct timespec when);
48 enum Time_spec
50 /* display only the date: 1999-03-25 */
51 TIME_SPEC_DATE=1,
52 /* display date and hour: 1999-03-25T03-0500 */
53 TIME_SPEC_HOURS,
54 /* display date, hours, and minutes: 1999-03-25T03:23-0500 */
55 TIME_SPEC_MINUTES,
56 /* display date, hours, minutes, and seconds: 1999-03-25T03:23:14-0500 */
57 TIME_SPEC_SECONDS
60 static char const *const time_spec_string[] =
62 "date", "hours", "minutes", "seconds", 0
65 static enum Time_spec const time_spec[] =
67 TIME_SPEC_DATE, TIME_SPEC_HOURS, TIME_SPEC_MINUTES, TIME_SPEC_SECONDS
70 /* The name this program was run with, for error messages. */
71 char *program_name;
73 /* If nonzero, display an ISO 8601 format date/time string */
74 static int iso_8601_format = 0;
76 /* If non-zero, display time in RFC-(2)822 format for mail or news. */
77 static int rfc_format = 0;
79 #define COMMON_SHORT_OPTIONS "Rd:f:r:s:u"
81 static struct option const long_options[] =
83 {"date", required_argument, NULL, 'd'},
84 {"file", required_argument, NULL, 'f'},
85 {"iso-8601", optional_argument, NULL, 'I'},
86 {"reference", required_argument, NULL, 'r'},
87 {"rfc-822", no_argument, NULL, 'R'},
88 {"set", required_argument, NULL, 's'},
89 {"uct", no_argument, NULL, 'u'},
90 {"utc", no_argument, NULL, 'u'},
91 {"universal", no_argument, NULL, 'u'},
92 {GETOPT_HELP_OPTION_DECL},
93 {GETOPT_VERSION_OPTION_DECL},
94 {NULL, 0, NULL, 0}
97 #if LOCALTIME_CACHE
98 # define TZSET tzset ()
99 #else
100 # define TZSET /* empty */
101 #endif
103 #ifdef _DATE_FMT
104 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
105 #else
106 # define DATE_FMT_LANGINFO() ""
107 #endif
109 void
110 usage (int status)
112 if (status != 0)
113 fprintf (stderr, _("Try `%s --help' for more information.\n"),
114 program_name);
115 else
117 printf (_("\
118 Usage: %s [OPTION]... [+FORMAT]\n\
119 or: %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\
121 program_name, program_name);
122 fputs (_("\
123 Display the current time in the given FORMAT, or set the system date.\n\
125 -d, --date=STRING display time described by STRING, not `now'\n\
126 -f, --file=DATEFILE like --date once for each line of DATEFILE\n\
127 -ITIMESPEC, --iso-8601[=TIMESPEC] output date/time in ISO 8601 format.\n\
128 TIMESPEC=`date' for date only,\n\
129 `hours', `minutes', or `seconds' for date and\n\
130 time to the indicated precision.\n\
131 --iso-8601 without TIMESPEC defaults to `date'.\n\
132 "), stdout);
133 fputs (_("\
134 -r, --reference=FILE display the last modification time of FILE\n\
135 -R, --rfc-822 output RFC-822 compliant date string\n\
136 -s, --set=STRING set time described by STRING\n\
137 -u, --utc, --universal print or set Coordinated Universal Time\n\
138 "), stdout);
139 fputs (HELP_OPTION_DESCRIPTION, stdout);
140 fputs (VERSION_OPTION_DESCRIPTION, stdout);
141 fputs (_("\
143 FORMAT controls the output. The only valid option for the second form\n\
144 specifies Coordinated Universal Time. Interpreted sequences are:\n\
146 %% a literal %\n\
147 %a locale's abbreviated weekday name (Sun..Sat)\n\
148 "), stdout);
149 fputs (_("\
150 %A locale's full weekday name, variable length (Sunday..Saturday)\n\
151 %b locale's abbreviated month name (Jan..Dec)\n\
152 %B locale's full month name, variable length (January..December)\n\
153 %c locale's date and time (Sat Nov 04 12:02:33 EST 1989)\n\
154 "), stdout);
155 fputs (_("\
156 %C century (year divided by 100 and truncated to an integer) [00-99]\n\
157 %d day of month (01..31)\n\
158 %D date (mm/dd/yy)\n\
159 %e day of month, blank padded ( 1..31)\n\
160 "), stdout);
161 fputs (_("\
162 %F same as %Y-%m-%d\n\
163 %g the 2-digit year corresponding to the %V week number\n\
164 %G the 4-digit year corresponding to the %V week number\n\
165 "), stdout);
166 fputs (_("\
167 %h same as %b\n\
168 %H hour (00..23)\n\
169 %I hour (01..12)\n\
170 %j day of year (001..366)\n\
171 "), stdout);
172 fputs (_("\
173 %k hour ( 0..23)\n\
174 %l hour ( 1..12)\n\
175 %m month (01..12)\n\
176 %M minute (00..59)\n\
177 "), stdout);
178 fputs (_("\
179 %n a newline\n\
180 %N nanoseconds (000000000..999999999)\n\
181 %p locale's upper case AM or PM indicator (blank in many locales)\n\
182 %P locale's lower case am or pm indicator (blank in many locales)\n\
183 %r time, 12-hour (hh:mm:ss [AP]M)\n\
184 %R time, 24-hour (hh:mm)\n\
185 %s seconds since `00:00:00 1970-01-01 UTC' (a GNU extension)\n\
186 "), stdout);
187 fputs (_("\
188 %S second (00..60); the 60 is necessary to accommodate a leap second\n\
189 %t a horizontal tab\n\
190 %T time, 24-hour (hh:mm:ss)\n\
191 %u day of week (1..7); 1 represents Monday\n\
192 "), stdout);
193 fputs (_("\
194 %U week number of year with Sunday as first day of week (00..53)\n\
195 %V week number of year with Monday as first day of week (01..53)\n\
196 %w day of week (0..6); 0 represents Sunday\n\
197 %W week number of year with Monday as first day of week (00..53)\n\
198 "), stdout);
199 fputs (_("\
200 %x locale's date representation (mm/dd/yy)\n\
201 %X locale's time representation (%H:%M:%S)\n\
202 %y last two digits of year (00..99)\n\
203 %Y year (1970...)\n\
204 "), stdout);
205 fputs (_("\
206 %z RFC-822 style numeric timezone (-0500) (a nonstandard extension)\n\
207 %Z time zone (e.g., EDT), or nothing if no time zone is determinable\n\
209 By default, date pads numeric fields with zeroes. GNU date recognizes\n\
210 the following modifiers between `%' and a numeric directive.\n\
212 `-' (hyphen) do not pad the field\n\
213 `_' (underscore) pad the field with spaces\n\
214 "), stdout);
215 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
217 exit (status);
220 /* Parse each line in INPUT_FILENAME as with --date and display each
221 resulting time and date. If the file cannot be opened, tell why
222 then exit. Issue a diagnostic for any lines that cannot be parsed.
223 If any line cannot be parsed, return nonzero; otherwise return zero. */
225 static int
226 batch_convert (const char *input_filename, const char *format)
228 int status;
229 FILE *in_stream;
230 char *line;
231 int line_length;
232 size_t buflen;
233 struct timespec when;
235 if (strcmp (input_filename, "-") == 0)
237 input_filename = _("standard input");
238 in_stream = stdin;
240 else
242 in_stream = fopen (input_filename, "r");
243 if (in_stream == NULL)
245 error (EXIT_FAILURE, errno, "`%s'", input_filename);
249 line = NULL;
250 buflen = 0;
251 status = 0;
252 while (1)
254 line_length = getline (&line, &buflen, in_stream);
255 if (line_length < 0)
257 /* FIXME: detect/handle error here. */
258 break;
261 when.tv_sec = get_date (line, NULL);
262 when.tv_nsec = 0; /* FIXME: get_date should set this. */
264 if (when.tv_sec == -1)
266 if (line[line_length - 1] == '\n')
267 line[line_length - 1] = '\0';
268 error (0, 0, _("invalid date `%s'"), line);
269 status = 1;
271 else
273 show_date (format, when);
277 if (fclose (in_stream) == EOF)
278 error (2, errno, "`%s'", input_filename);
280 if (line != NULL)
281 free (line);
283 return status;
287 main (int argc, char **argv)
289 int optc;
290 const char *datestr = NULL;
291 const char *set_datestr = NULL;
292 struct timespec when;
293 int set_date = 0;
294 char *format;
295 char *batch_file = NULL;
296 char *reference = NULL;
297 struct stat refstats;
298 int n_args;
299 int status;
300 int option_specified_date;
301 char const *short_options = (posix2_version () < 200112
302 ? COMMON_SHORT_OPTIONS "I::"
303 : COMMON_SHORT_OPTIONS "I:");
305 program_name = argv[0];
306 setlocale (LC_ALL, "");
307 bindtextdomain (PACKAGE, LOCALEDIR);
308 textdomain (PACKAGE);
310 close_stdout_set_status (2);
311 atexit (close_stdout);
313 while ((optc = getopt_long (argc, argv, short_options, long_options, NULL))
314 != -1)
315 switch (optc)
317 case 0:
318 break;
319 case 'd':
320 datestr = optarg;
321 break;
322 case 'f':
323 batch_file = optarg;
324 break;
325 case 'I':
326 iso_8601_format = (optarg
327 ? XARGMATCH ("--iso-8601", optarg,
328 time_spec_string, time_spec)
329 : TIME_SPEC_DATE);
330 break;
331 case 'r':
332 reference = optarg;
333 break;
334 case 'R':
335 rfc_format = 1;
336 break;
337 case 's':
338 set_datestr = optarg;
339 set_date = 1;
340 break;
341 case 'u':
342 /* POSIX says that `date -u' is equivalent to setting the TZ
343 environment variable, so this option should do nothing other
344 than setting TZ. */
345 if (putenv ("TZ=UTC0") != 0)
346 xalloc_die ();
347 TZSET;
348 break;
349 case_GETOPT_HELP_CHAR;
350 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
351 default:
352 usage (EXIT_FAILURE);
355 n_args = argc - optind;
357 option_specified_date = ((datestr ? 1 : 0)
358 + (batch_file ? 1 : 0)
359 + (reference ? 1 : 0));
361 if (option_specified_date > 1)
363 error (0, 0,
364 _("the options to specify dates for printing are mutually exclusive"));
365 usage (EXIT_FAILURE);
368 if (set_date && option_specified_date)
370 error (0, 0,
371 _("the options to print and set the time may not be used together"));
372 usage (EXIT_FAILURE);
375 if (n_args > 1)
377 error (0, 0, _("too many non-option arguments: %s%s"),
378 argv[optind + 1], n_args == 2 ? "" : " ...");
379 usage (EXIT_FAILURE);
382 if ((set_date || option_specified_date)
383 && n_args == 1 && argv[optind][0] != '+')
385 error (0, 0, _("\
386 the argument `%s' lacks a leading `+';\n\
387 When using an option to specify date(s), any non-option\n\
388 argument must be a format string beginning with `+'."),
389 argv[optind]);
390 usage (EXIT_FAILURE);
393 /* Simply ignore --rfc-822 if specified when setting the date. */
394 if (rfc_format && !set_date && n_args > 0)
396 error (0, 0,
397 _("a format string may not be specified when using\
398 the --rfc-822 (-R) option"));
399 usage (EXIT_FAILURE);
402 if (set_date)
403 datestr = set_datestr;
405 if (batch_file != NULL)
407 status = batch_convert (batch_file,
408 (n_args == 1 ? argv[optind] + 1 : NULL));
410 else
412 bool valid_date = true;
413 status = 0;
415 if (!option_specified_date && !set_date)
417 if (n_args == 1 && argv[optind][0] != '+')
419 /* Prepare to set system clock to the specified date/time
420 given in the POSIX-format. */
421 set_date = 1;
422 datestr = argv[optind];
423 valid_date = posixtime (&when.tv_sec,
424 datestr,
425 (PDS_TRAILING_YEAR
426 | PDS_CENTURY | PDS_SECONDS));
427 when.tv_nsec = 0; /* FIXME: posixtime should set this. */
428 format = NULL;
430 else
432 /* Prepare to print the current date/time. */
433 datestr = _("undefined");
434 if (gettime (&when) != 0)
435 error (EXIT_FAILURE, errno, _("cannot get time of day"));
436 format = (n_args == 1 ? argv[optind] + 1 : NULL);
439 else
441 /* (option_specified_date || set_date) */
442 if (reference != NULL)
444 if (stat (reference, &refstats))
445 error (EXIT_FAILURE, errno, "%s", reference);
446 when.tv_sec = refstats.st_mtime;
447 when.tv_nsec = TIMESPEC_NS (refstats.st_mtim);
449 else
451 when.tv_sec = get_date (datestr, NULL);
452 when.tv_nsec = 0; /* FIXME: get_date should set this. */
453 valid_date = (when.tv_sec != (time_t) -1);
456 format = (n_args == 1 ? argv[optind] + 1 : NULL);
459 if (! valid_date)
460 error (EXIT_FAILURE, 0, _("invalid date `%s'"), datestr);
462 if (set_date)
464 /* Set the system clock to the specified date, then regardless of
465 the success of that operation, format and print that date. */
466 if (settime (&when) != 0)
468 error (0, errno, _("cannot set date"));
469 status = 1;
473 show_date (format, when);
476 exit (status);
479 /* Display the date and/or time in WHEN according to the format specified
480 in FORMAT, followed by a newline. If FORMAT is NULL, use the
481 standard output format (ctime style but with a timezone inserted). */
483 static void
484 show_date (const char *format, struct timespec when)
486 struct tm *tm;
487 char *out = NULL;
488 size_t out_length = 0;
489 /* ISO 8601 formats. See below regarding %z */
490 static char const * const iso_format_string[] =
492 "%Y-%m-%d",
493 "%Y-%m-%dT%H%z",
494 "%Y-%m-%dT%H:%M%z",
495 "%Y-%m-%dT%H:%M:%S%z"
498 tm = localtime (&when.tv_sec);
500 if (format == NULL)
502 if (rfc_format)
503 format = "%a, %d %b %Y %H:%M:%S %z";
504 else if (iso_8601_format)
505 format = iso_format_string[iso_8601_format - 1];
506 else
508 char *date_fmt = DATE_FMT_LANGINFO ();
509 /* Do not wrap the following literal format string with _(...).
510 For example, suppose LC_ALL is unset, LC_TIME="POSIX",
511 and LANG="ko_KR". In that case, POSIX says that LC_TIME
512 determines the format and contents of date and time strings
513 written by date, which means "date" must generate output
514 using the POSIX locale; but adding _() would cause "date"
515 to use a Korean translation of the format. */
516 format = *date_fmt ? date_fmt : "%a %b %e %H:%M:%S %Z %Y";
519 else if (*format == '\0')
521 printf ("\n");
522 return;
525 while (1)
527 int done;
528 out_length += 200;
529 out = (char *) xrealloc (out, out_length);
531 /* Mark the first byte of the buffer so we can detect the case
532 of nstrftime producing an empty string. Otherwise, this loop
533 would not terminate when date was invoked like this
534 `LANG=de date +%p' on a system with good language support. */
535 out[0] = '\1';
537 if (rfc_format)
538 setlocale (LC_ALL, "C");
540 done = (nstrftime (out, out_length, format, tm, 0, when.tv_nsec)
541 || out[0] == '\0');
543 if (rfc_format)
544 setlocale (LC_ALL, "");
546 if (done)
547 break;
550 printf ("%s\n", out);
551 free (out);