1 /* date - print or set the system date and time
2 Copyright (C) 1989-2003 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 (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 initialize_main (&argc, &argv);
306 program_name = argv[0];
307 setlocale (LC_ALL, "");
308 bindtextdomain (PACKAGE, LOCALEDIR);
309 textdomain (PACKAGE);
311 close_stdout_set_status (2);
312 atexit (close_stdout);
314 while ((optc = getopt_long (argc, argv, short_options, long_options, NULL))
327 iso_8601_format = (optarg
328 ? XARGMATCH ("--iso-8601", optarg,
329 time_spec_string, time_spec)
339 set_datestr = optarg;
343 /* POSIX says that `date -u' is equivalent to setting the TZ
344 environment variable, so this option should do nothing other
346 if (putenv ("TZ=UTC0") != 0)
350 case_GETOPT_HELP_CHAR;
351 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
353 usage (EXIT_FAILURE);
356 n_args = argc - optind;
358 option_specified_date = ((datestr ? 1 : 0)
359 + (batch_file ? 1 : 0)
360 + (reference ? 1 : 0));
362 if (option_specified_date > 1)
365 _("the options to specify dates for printing are mutually exclusive"));
366 usage (EXIT_FAILURE);
369 if (set_date && option_specified_date)
372 _("the options to print and set the time may not be used together"));
373 usage (EXIT_FAILURE);
378 error (0, 0, _("too many non-option arguments: %s%s"),
379 argv[optind + 1], n_args == 2 ? "" : " ...");
380 usage (EXIT_FAILURE);
383 if ((set_date || option_specified_date)
384 && n_args == 1 && argv[optind][0] != '+')
387 the argument `%s' lacks a leading `+';\n\
388 When using an option to specify date(s), any non-option\n\
389 argument must be a format string beginning with `+'."),
391 usage (EXIT_FAILURE);
394 /* Simply ignore --rfc-822 if specified when setting the date. */
395 if (rfc_format && !set_date && n_args > 0)
398 _("a format string may not be specified when using\
399 the --rfc-822 (-R) option"));
400 usage (EXIT_FAILURE);
404 datestr = set_datestr;
406 if (batch_file != NULL)
408 status = batch_convert (batch_file,
409 (n_args == 1 ? argv[optind] + 1 : NULL));
413 bool valid_date = true;
416 if (!option_specified_date && !set_date)
418 if (n_args == 1 && argv[optind][0] != '+')
420 /* Prepare to set system clock to the specified date/time
421 given in the POSIX-format. */
423 datestr = argv[optind];
424 valid_date = posixtime (&when.tv_sec,
427 | PDS_CENTURY | PDS_SECONDS));
428 when.tv_nsec = 0; /* FIXME: posixtime should set this. */
433 /* Prepare to print the current date/time. */
434 datestr = _("undefined");
435 if (gettime (&when) != 0)
436 error (EXIT_FAILURE, errno, _("cannot get time of day"));
437 format = (n_args == 1 ? argv[optind] + 1 : NULL);
442 /* (option_specified_date || set_date) */
443 if (reference != NULL)
445 if (stat (reference, &refstats))
446 error (EXIT_FAILURE, errno, "%s", reference);
447 when.tv_sec = refstats.st_mtime;
448 when.tv_nsec = TIMESPEC_NS (refstats.st_mtim);
452 when.tv_sec = get_date (datestr, NULL);
453 when.tv_nsec = 0; /* FIXME: get_date should set this. */
454 valid_date = (when.tv_sec != (time_t) -1);
457 format = (n_args == 1 ? argv[optind] + 1 : NULL);
461 error (EXIT_FAILURE, 0, _("invalid date `%s'"), datestr);
465 /* Set the system clock to the specified date, then regardless of
466 the success of that operation, format and print that date. */
467 if (settime (&when) != 0)
469 error (0, errno, _("cannot set date"));
474 show_date (format, when);
480 /* Display the date and/or time in WHEN according to the format specified
481 in FORMAT, followed by a newline. If FORMAT is NULL, use the
482 standard output format (ctime style but with a timezone inserted). */
485 show_date (const char *format, struct timespec when)
489 size_t out_length = 0;
490 /* ISO 8601 formats. See below regarding %z */
491 static char const * const iso_format_string[] =
496 "%Y-%m-%dT%H:%M:%S%z"
499 tm = localtime (&when.tv_sec);
504 format = "%a, %d %b %Y %H:%M:%S %z";
505 else if (iso_8601_format)
506 format = iso_format_string[iso_8601_format - 1];
509 char *date_fmt = DATE_FMT_LANGINFO ();
510 /* Do not wrap the following literal format string with _(...).
511 For example, suppose LC_ALL is unset, LC_TIME="POSIX",
512 and LANG="ko_KR". In that case, POSIX says that LC_TIME
513 determines the format and contents of date and time strings
514 written by date, which means "date" must generate output
515 using the POSIX locale; but adding _() would cause "date"
516 to use a Korean translation of the format. */
517 format = *date_fmt ? date_fmt : "%a %b %e %H:%M:%S %Z %Y";
520 else if (*format == '\0')
530 out = xrealloc (out, out_length);
532 /* Mark the first byte of the buffer so we can detect the case
533 of nstrftime producing an empty string. Otherwise, this loop
534 would not terminate when date was invoked like this
535 `LANG=de date +%p' on a system with good language support. */
539 setlocale (LC_ALL, "C");
541 done = (nstrftime (out, out_length, format, tm, 0, when.tv_nsec)
545 setlocale (LC_ALL, "");
551 printf ("%s\n", out);