1 /* date - print or set the system date and time
2 Copyright (C) 1989-2012 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> */
22 #include <sys/types.h>
23 #if HAVE_LANGINFO_CODESET
24 # include <langinfo.h>
30 #include "parse-datetime.h"
33 #include "stat-time.h"
34 #include "fprintftime.h"
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "date"
39 #define AUTHORS proper_name ("David MacKenzie")
41 static bool show_date (const char *format
, struct timespec when
);
45 /* Display only the date. */
47 /* Display date, hours, minutes, and seconds. */
49 /* Similar, but display nanoseconds. */
52 /* Put these last, since they aren't valid for --rfc-3339. */
54 /* Display date and hour. */
56 /* Display date, hours, and minutes. */
60 static char const *const time_spec_string
[] =
62 /* Put "hours" and "minutes" first, since they aren't valid for
65 "date", "seconds", "ns", NULL
67 static enum Time_spec
const time_spec
[] =
69 TIME_SPEC_HOURS
, TIME_SPEC_MINUTES
,
70 TIME_SPEC_DATE
, TIME_SPEC_SECONDS
, TIME_SPEC_NS
72 ARGMATCH_VERIFY (time_spec_string
, time_spec
);
74 /* A format suitable for Internet RFC 2822. */
75 static char const rfc_2822_format
[] = "%a, %d %b %Y %H:%M:%S %z";
77 /* For long options that have no equivalent short option, use a
78 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
81 RFC_3339_OPTION
= CHAR_MAX
+ 1
84 static char const short_options
[] = "d:f:I::r:Rs:u";
86 static struct option
const long_options
[] =
88 {"date", required_argument
, NULL
, 'd'},
89 {"file", required_argument
, NULL
, 'f'},
90 {"iso-8601", optional_argument
, NULL
, 'I'},
91 {"reference", required_argument
, NULL
, 'r'},
92 {"rfc-822", no_argument
, NULL
, 'R'},
93 {"rfc-2822", no_argument
, NULL
, 'R'},
94 {"rfc-3339", required_argument
, NULL
, RFC_3339_OPTION
},
95 {"set", required_argument
, NULL
, 's'},
96 {"uct", no_argument
, NULL
, 'u'},
97 {"utc", no_argument
, NULL
, 'u'},
98 {"universal", no_argument
, NULL
, 'u'},
99 {GETOPT_HELP_OPTION_DECL
},
100 {GETOPT_VERSION_OPTION_DECL
},
105 # define TZSET tzset ()
107 # define TZSET /* empty */
111 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
113 # define DATE_FMT_LANGINFO() ""
119 if (status
!= EXIT_SUCCESS
)
120 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
125 Usage: %s [OPTION]... [+FORMAT]\n\
126 or: %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\
128 program_name
, program_name
);
130 Display the current time in the given FORMAT, or set the system date.\n\
132 -d, --date=STRING display time described by STRING, not `now'\n\
133 -f, --file=DATEFILE like --date once for each line of DATEFILE\n\
134 -I[TIMESPEC], --iso-8601[=TIMESPEC] output date/time in ISO 8601 format.\n\
135 TIMESPEC=`date' for date only (the default),\n\
136 `hours', `minutes', `seconds', or `ns' for date\n\
137 and time to the indicated precision.\n\
140 -r, --reference=FILE display the last modification time of FILE\n\
141 -R, --rfc-2822 output date and time in RFC 2822 format.\n\
142 Example: Mon, 07 Aug 2006 12:34:56 -0600\n\
145 --rfc-3339=TIMESPEC output date and time in RFC 3339 format.\n\
146 TIMESPEC=`date', `seconds', or `ns' for\n\
147 date and time to the indicated precision.\n\
148 Date and time components are separated by\n\
149 a single space: 2006-08-07 12:34:56-06:00\n\
150 -s, --set=STRING set time described by STRING\n\
151 -u, --utc, --universal print or set Coordinated Universal Time\n\
153 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
154 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
157 FORMAT controls the output. Interpreted sequences are:\n\
160 %a locale's abbreviated weekday name (e.g., Sun)\n\
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\
169 %C century; like %Y, except omit last two digits (e.g., 20)\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\
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\
183 %j day of year (001..366)\n\
186 %k hour, space padded ( 0..23); same as %_H\n\
187 %l hour, space padded ( 1..12); same as %_I\n\
189 %M minute (00..59)\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\
201 %S second (00..60)\n\
203 %T time; same as %H:%M:%S\n\
204 %u day of week (1..7); 1 is Monday\n\
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\
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\
219 %z +hhmm numeric time zone (e.g., -0400)\n\
220 %:z +hh:mm numeric time zone (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\
228 The following optional flags may follow `%':\n\
230 - (hyphen) do not pad the field\n\
231 _ (underscore) pad with spaces\n\
232 0 (zero) pad with zeros\n\
233 ^ use upper case if possible\n\
234 # use opposite case if possible\n\
238 After any flags comes an optional field width, as a decimal number;\n\
239 then an optional modifier, which is either\n\
240 E to use the locale's alternate representations if available, or\n\
241 O to use the locale's alternate numeric symbols if available.\n\
246 Convert seconds since the epoch (1970-01-01 UTC) to a date\n\
247 $ date --date='@2147483647'\n\
249 Show the time on the west coast of the US (use tzselect(1) to find TZ)\n\
250 $ TZ='America/Los_Angeles' date\n\
252 Show the local time for 9AM next Friday on the west coast of the US\n\
253 $ date --date='TZ=\"America/Los_Angeles\" 09:00 next Fri'\n\
255 emit_ancillary_info ();
260 /* Parse each line in INPUT_FILENAME as with --date and display each
261 resulting time and date. If the file cannot be opened, tell why
262 then exit. Issue a diagnostic for any lines that cannot be parsed.
263 Return true if successful. */
266 batch_convert (const char *input_filename
, const char *format
)
272 struct timespec when
;
274 if (STREQ (input_filename
, "-"))
276 input_filename
= _("standard input");
281 in_stream
= fopen (input_filename
, "r");
282 if (in_stream
== NULL
)
284 error (EXIT_FAILURE
, errno
, "%s", quote (input_filename
));
293 ssize_t line_length
= getline (&line
, &buflen
, in_stream
);
296 /* FIXME: detect/handle error here. */
300 if (! parse_datetime (&when
, line
, NULL
))
302 if (line
[line_length
- 1] == '\n')
303 line
[line_length
- 1] = '\0';
304 error (0, 0, _("invalid date %s"), quote (line
));
309 ok
&= show_date (format
, when
);
313 if (fclose (in_stream
) == EOF
)
314 error (EXIT_FAILURE
, errno
, "%s", quote (input_filename
));
322 main (int argc
, char **argv
)
325 const char *datestr
= NULL
;
326 const char *set_datestr
= NULL
;
327 struct timespec when
;
328 bool set_date
= false;
329 char const *format
= NULL
;
330 char *batch_file
= NULL
;
331 char *reference
= NULL
;
332 struct stat refstats
;
334 int option_specified_date
;
336 initialize_main (&argc
, &argv
);
337 set_program_name (argv
[0]);
338 setlocale (LC_ALL
, "");
339 bindtextdomain (PACKAGE
, LOCALEDIR
);
340 textdomain (PACKAGE
);
342 atexit (close_stdout
);
344 while ((optc
= getopt_long (argc
, argv
, short_options
, long_options
, NULL
))
347 char const *new_format
= NULL
;
357 case RFC_3339_OPTION
:
359 static char const rfc_3339_format
[][32] =
362 "%Y-%m-%d %H:%M:%S%:z",
363 "%Y-%m-%d %H:%M:%S.%N%:z"
366 XARGMATCH ("--rfc-3339", optarg
,
367 time_spec_string
+ 2, time_spec
+ 2);
368 new_format
= rfc_3339_format
[i
];
373 static char const iso_8601_format
[][32] =
376 "%Y-%m-%dT%H:%M:%S%z",
377 "%Y-%m-%dT%H:%M:%S,%N%z",
383 ? XARGMATCH ("--iso-8601", optarg
, time_spec_string
, time_spec
)
385 new_format
= iso_8601_format
[i
];
392 new_format
= rfc_2822_format
;
395 set_datestr
= optarg
;
399 /* POSIX says that `date -u' is equivalent to setting the TZ
400 environment variable, so this option should do nothing other
402 if (putenv (bad_cast ("TZ=UTC0")) != 0)
406 case_GETOPT_HELP_CHAR
;
407 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
409 usage (EXIT_FAILURE
);
415 error (EXIT_FAILURE
, 0, _("multiple output formats specified"));
420 option_specified_date
= ((datestr
? 1 : 0)
421 + (batch_file
? 1 : 0)
422 + (reference
? 1 : 0));
424 if (option_specified_date
> 1)
427 _("the options to specify dates for printing are mutually exclusive"));
428 usage (EXIT_FAILURE
);
431 if (set_date
&& option_specified_date
)
434 _("the options to print and set the time may not be used together"));
435 usage (EXIT_FAILURE
);
440 if (optind
+ 1 < argc
)
442 error (0, 0, _("extra operand %s"), quote (argv
[optind
+ 1]));
443 usage (EXIT_FAILURE
);
446 if (argv
[optind
][0] == '+')
449 error (EXIT_FAILURE
, 0, _("multiple output formats specified"));
450 format
= argv
[optind
++] + 1;
452 else if (set_date
|| option_specified_date
)
455 _("the argument %s lacks a leading `+';\n"
456 "when using an option to specify date(s), any non-option\n"
457 "argument must be a format string beginning with `+'"),
458 quote (argv
[optind
]));
459 usage (EXIT_FAILURE
);
465 format
= DATE_FMT_LANGINFO ();
468 /* Do not wrap the following literal format string with _(...).
469 For example, suppose LC_ALL is unset, LC_TIME=POSIX,
470 and LANG="ko_KR". In that case, POSIX says that LC_TIME
471 determines the format and contents of date and time strings
472 written by date, which means "date" must generate output
473 using the POSIX locale; but adding _() would cause "date"
474 to use a Korean translation of the format. */
475 format
= "%a %b %e %H:%M:%S %Z %Y";
479 if (batch_file
!= NULL
)
480 ok
= batch_convert (batch_file
, format
);
483 bool valid_date
= true;
486 if (!option_specified_date
&& !set_date
)
490 /* Prepare to set system clock to the specified date/time
491 given in the POSIX-format. */
493 datestr
= argv
[optind
];
494 valid_date
= posixtime (&when
.tv_sec
,
497 | PDS_CENTURY
| PDS_SECONDS
));
498 when
.tv_nsec
= 0; /* FIXME: posixtime should set this. */
502 /* Prepare to print the current date/time. */
508 /* (option_specified_date || set_date) */
509 if (reference
!= NULL
)
511 if (stat (reference
, &refstats
) != 0)
512 error (EXIT_FAILURE
, errno
, "%s", reference
);
513 when
= get_stat_mtime (&refstats
);
518 datestr
= set_datestr
;
519 valid_date
= parse_datetime (&when
, datestr
, NULL
);
524 error (EXIT_FAILURE
, 0, _("invalid date %s"), quote (datestr
));
528 /* Set the system clock to the specified date, then regardless of
529 the success of that operation, format and print that date. */
530 if (settime (&when
) != 0)
532 error (0, errno
, _("cannot set date"));
537 ok
&= show_date (format
, when
);
540 exit (ok
? EXIT_SUCCESS
: EXIT_FAILURE
);
543 /* Display the date and/or time in WHEN according to the format specified
544 in FORMAT, followed by a newline. Return true if successful. */
547 show_date (const char *format
, struct timespec when
)
551 tm
= localtime (&when
.tv_sec
);
554 char buf
[INT_BUFSIZE_BOUND (intmax_t)];
555 error (0, 0, _("time %s is out of range"), timetostr (when
.tv_sec
, buf
));
559 if (format
== rfc_2822_format
)
560 setlocale (LC_TIME
, "C");
561 fprintftime (stdout
, format
, tm
, 0, when
.tv_nsec
);
562 fputc ('\n', stdout
);
563 if (format
== rfc_2822_format
)
564 setlocale (LC_TIME
, "");