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)
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> */
23 #include <sys/types.h>
24 #if HAVE_LANGINFO_CODESET
25 # include <langinfo.h>
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "date"
42 #define AUTHORS "David MacKenzie"
46 static void show_date PARAMS ((const char *format, struct timespec when));
50 /* display only the date: 1999-03-25 */
52 /* display date and hour: 1999-03-25T03-0500 */
54 /* display date, hours, and minutes: 1999-03-25T03:23-0500 */
56 /* display date, hours, minutes, and seconds: 1999-03-25T03:23:14-0500 */
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. */
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},
98 # define TZSET tzset ()
100 # define TZSET /* empty */
104 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
106 # define DATE_FMT_LANGINFO() ""
113 fprintf (stderr, _("Try `%s --help' for more information.\n"),
118 Usage: %s [OPTION]... [+FORMAT]\n\
119 or: %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\
121 program_name, program_name);
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\
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\
139 fputs (HELP_OPTION_DESCRIPTION, stdout);
140 fputs (VERSION_OPTION_DESCRIPTION, stdout);
143 FORMAT controls the output. The only valid option for the second form\n\
144 specifies Coordinated Universal Time. Interpreted sequences are:\n\
147 %a locale's abbreviated weekday name (Sun..Sat)\n\
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\
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\
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\
170 %j day of year (001..366)\n\
176 %M minute (00..59)\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\
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\
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\
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\
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\
215 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
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. */
226 batch_convert (const char *input_filename, const char *format)
233 struct timespec when;
235 if (strcmp (input_filename, "-") == 0)
237 input_filename = _("standard input");
242 in_stream = fopen (input_filename, "r");
243 if (in_stream == NULL)
245 error (EXIT_FAILURE, errno, "`%s'", input_filename);
254 line_length = getline (&line, &buflen, in_stream);
257 /* FIXME: detect/handle error here. */
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);
273 show_date (format, when);
277 if (fclose (in_stream) == EOF)
278 error (2, errno, "`%s'", input_filename);
287 main (int argc, char **argv)
290 const char *datestr = NULL;
291 const char *set_datestr = NULL;
292 struct timespec when;
295 char *batch_file = NULL;
296 char *reference = NULL;
297 struct stat refstats;
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))
326 iso_8601_format = (optarg
327 ? XARGMATCH ("--iso-8601", optarg,
328 time_spec_string, time_spec)
338 set_datestr = optarg;
342 /* POSIX says that `date -u' is equivalent to setting the TZ
343 environment variable, so this option should do nothing other
345 if (putenv ("TZ=UTC0") != 0)
349 case_GETOPT_HELP_CHAR;
350 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
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)
364 _("the options to specify dates for printing are mutually exclusive"));
365 usage (EXIT_FAILURE);
368 if (set_date && option_specified_date)
371 _("the options to print and set the time may not be used together"));
372 usage (EXIT_FAILURE);
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] != '+')
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 `+'."),
390 usage (EXIT_FAILURE);
393 /* Simply ignore --rfc-822 if specified when setting the date. */
394 if (rfc_format && !set_date && n_args > 0)
397 _("a format string may not be specified when using\
398 the --rfc-822 (-R) option"));
399 usage (EXIT_FAILURE);
403 datestr = set_datestr;
405 if (batch_file != NULL)
407 status = batch_convert (batch_file,
408 (n_args == 1 ? argv[optind] + 1 : NULL));
412 bool valid_date = true;
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. */
422 datestr = argv[optind];
423 valid_date = posixtime (&when.tv_sec,
426 | PDS_CENTURY | PDS_SECONDS));
427 when.tv_nsec = 0; /* FIXME: posixtime should set this. */
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);
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);
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);
460 error (EXIT_FAILURE, 0, _("invalid date `%s'"), datestr);
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"));
473 show_date (format, when);
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). */
484 show_date (const char *format, struct timespec when)
488 size_t out_length = 0;
489 /* ISO 8601 formats. See below regarding %z */
490 static char const * const iso_format_string[] =
495 "%Y-%m-%dT%H:%M:%S%z"
498 tm = localtime (&when.tv_sec);
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];
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')
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. */
538 setlocale (LC_ALL, "C");
540 done = (nstrftime (out, out_length, format, tm, 0, when.tv_nsec)
544 setlocale (LC_ALL, "");
550 printf ("%s\n", out);