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