(usage): Correct error in %V description.
[platform/upstream/coreutils.git] / src / date.c
1 /* date - print or set the system date and time
2    Copyright (C) 1989-2000 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
25 #include "system.h"
26 #include "argmatch.h"
27 #include "closeout.h"
28 #include "error.h"
29 #include "getdate.h"
30 #include "getline.h"
31 #include "posixtm.h"
32
33 /* The official name of this program (e.g., no `g' prefix).  */
34 #define PROGRAM_NAME "date"
35
36 #define AUTHORS "David MacKenzie"
37
38 #ifndef STDC_HEADERS
39 size_t strftime ();
40 time_t time ();
41 #endif
42
43 int putenv ();
44 int stime ();
45
46 static void show_date PARAMS ((const char *format, time_t when));
47
48 enum Time_spec
49 {
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
58 };
59
60 static char const *const time_spec_string[] =
61 {
62   "date", "hours", "minutes", "seconds", 0
63 };
64
65 static enum Time_spec const time_spec[] =
66 {
67   TIME_SPEC_DATE, TIME_SPEC_HOURS, TIME_SPEC_MINUTES, TIME_SPEC_SECONDS
68 };
69
70 /* The name this program was run with, for error messages. */
71 char *program_name;
72
73 /* If nonzero, display an ISO 8601 format date/time string */
74 static int iso_8601_format = 0;
75
76 /* If non-zero, display time in RFC-822 format for mail or news. */
77 static int rfc_format = 0;
78
79 /* If nonzero, print or set Coordinated Universal Time.  */
80 static int universal_time = 0;
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 #define TZ_UTC0 "TZ=UTC0"
99
100 #if LOCALTIME_CACHE
101 # define TZSET tzset ()
102 #else
103 # define TZSET /* empty */
104 #endif
105
106 #define MAYBE_SET_TZ_UTC0 \
107   do { if (universal_time) set_tz (TZ_UTC0); } while (0)
108
109 void
110 usage (int status)
111 {
112   if (status != 0)
113     fprintf (stderr, _("Try `%s --help' for more information.\n"),
114              program_name);
115   else
116     {
117       printf (_("\
118 Usage: %s [OPTION]... [+FORMAT]\n\
119   or:  %s [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\
120 "),
121               program_name, program_name);
122       printf (_("\
123 Display the current time in the given FORMAT, or set the system date.\n\
124 \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   -I, --iso-8601[=TIMESPEC] output an ISO-8601 compliant date/time string.\n\
128                             TIMESPEC=`date' (or missing) for date only,\n\
129                             `hours', `minutes', or `seconds' for date and\n\
130                             time to the indicated precision.\n\
131   -r, --reference=FILE      display the last modification time of FILE\n\
132   -R, --rfc-822             output RFC-822 compliant date string\n\
133   -s, --set=STRING          set time described by STRING\n\
134   -u, --utc, --universal    print or set Coordinated Universal Time\n\
135       --help                display this help and exit\n\
136       --version             output version information and exit\n\
137 "));
138       printf (_("\
139 \n\
140 FORMAT controls the output.  The only valid option for the second form\n\
141 specifies Coordinated Universal Time.  Interpreted sequences are:\n\
142 \n\
143   %%%%   a literal %%\n\
144   %%a   locale's abbreviated weekday name (Sun..Sat)\n\
145   %%A   locale's full weekday name, variable length (Sunday..Saturday)\n\
146   %%b   locale's abbreviated month name (Jan..Dec)\n\
147   %%B   locale's full month name, variable length (January..December)\n\
148   %%c   locale's date and time (Sat Nov 04 12:02:33 EST 1989)\n\
149   %%d   day of month (01..31)\n\
150   %%D   date (mm/dd/yy)\n\
151   %%e   day of month, blank padded ( 1..31)\n\
152   %%h   same as %%b\n\
153   %%H   hour (00..23)\n\
154   %%I   hour (01..12)\n\
155   %%j   day of year (001..366)\n\
156   %%k   hour ( 0..23)\n\
157   %%l   hour ( 1..12)\n\
158   %%m   month (01..12)\n\
159   %%M   minute (00..59)\n\
160   %%n   a newline\n\
161   %%p   locale's AM or PM\n\
162   %%r   time, 12-hour (hh:mm:ss [AP]M)\n\
163   %%s   seconds since 00:00:00, Jan 1, 1970 (a GNU extension)\n\
164   %%S   second (00..60)\n\
165   %%t   a horizontal tab\n\
166   %%T   time, 24-hour (hh:mm:ss)\n\
167   %%U   week number of year with Sunday as first day of week (00..53)\n\
168   %%V   week number of year with Monday as first day of week (01..53)\n\
169   %%w   day of week (0..6);  0 represents Sunday\n\
170   %%W   week number of year with Monday as first day of week (00..53)\n\
171   %%x   locale's date representation (mm/dd/yy)\n\
172   %%X   locale's time representation (%%H:%%M:%%S)\n\
173   %%y   last two digits of year (00..99)\n\
174   %%Y   year (1970...)\n\
175   %%z   RFC-822 style numeric timezone (-0500) (a nonstandard extension)\n\
176   %%Z   time zone (e.g., EDT), or nothing if no time zone is determinable\n\
177 \n\
178 By default, date pads numeric fields with zeroes.  GNU date recognizes\n\
179 the following modifiers between `%%' and a numeric directive.\n\
180 \n\
181   `-' (hyphen) do not pad the field\n\
182   `_' (underscore) pad the field with spaces\n\
183 "));
184       puts (_("\nReport bugs to <bug-sh-utils@gnu.org>."));
185     }
186   exit (status);
187 }
188
189 /* Set the TZ environment variable.  */
190
191 static void
192 set_tz (const char *tz_eq_zone)
193 {
194   if (putenv (tz_eq_zone) != 0)
195     error (1, 0, "memory exhausted");
196   TZSET;
197 }
198
199 /* Parse each line in INPUT_FILENAME as with --date and display each
200    resulting time and date.  If the file cannot be opened, tell why
201    then exit.  Issue a diagnostic for any lines that cannot be parsed.
202    If any line cannot be parsed, return nonzero;  otherwise return zero.  */
203
204 static int
205 batch_convert (const char *input_filename, const char *format)
206 {
207   int status;
208   FILE *in_stream;
209   char *line;
210   int line_length;
211   size_t buflen;
212   time_t when;
213   char *initial_TZ IF_LINT (= NULL);
214
215   if (strcmp (input_filename, "-") == 0)
216     {
217       input_filename = _("standard input");
218       in_stream = stdin;
219     }
220   else
221     {
222       in_stream = fopen (input_filename, "r");
223       if (in_stream == NULL)
224         {
225           error (1, errno, "`%s'", input_filename);
226         }
227     }
228
229   line = NULL;
230   buflen = 0;
231
232   if (universal_time)
233     {
234       initial_TZ = getenv ("TZ");
235       if (initial_TZ == NULL)
236         {
237           initial_TZ = xstrdup ("TZ=");
238         }
239       else
240         {
241           size_t tz_len = strlen (initial_TZ);
242           char *buf = xmalloc (3 + tz_len + 1);
243           memcpy (mempcpy (buf, "TZ=", 3), initial_TZ, tz_len + 1);
244           initial_TZ = buf;
245         }
246     }
247
248   status = 0;
249   while (1)
250     {
251       line_length = getline (&line, &buflen, in_stream);
252       if (line_length < 0)
253         {
254           /* FIXME: detect/handle error here.  */
255           break;
256         }
257
258       if (universal_time)
259         {
260           /* When given a universal time option, restore the initial
261              value of TZ before parsing each string.  */
262           set_tz (initial_TZ);
263         }
264
265       when = get_date (line, NULL);
266
267       if (when == -1)
268         {
269           if (line[line_length - 1] == '\n')
270             line[line_length - 1] = '\0';
271           error (0, 0, _("invalid date `%s'"), line);
272           status = 1;
273         }
274       else
275         {
276           MAYBE_SET_TZ_UTC0;
277           show_date (format, when);
278         }
279     }
280
281   free (initial_TZ);
282
283   if (fclose (in_stream) == EOF)
284     error (2, errno, "`%s'", input_filename);
285
286   if (line != NULL)
287     free (line);
288
289   return status;
290 }
291
292 int
293 main (int argc, char **argv)
294 {
295   int optc;
296   const char *datestr = NULL;
297   const char *set_datestr = NULL;
298   time_t when;
299   int set_date = 0;
300   char *format;
301   char *batch_file = NULL;
302   char *reference = NULL;
303   struct stat refstats;
304   int n_args;
305   int status;
306   int option_specified_date;
307
308   program_name = argv[0];
309   setlocale (LC_ALL, "");
310   bindtextdomain (PACKAGE, LOCALEDIR);
311   textdomain (PACKAGE);
312
313   while ((optc = getopt_long (argc, argv, "d:f:I::r:Rs:u", long_options, NULL))
314          != -1)
315     switch (optc)
316       {
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         universal_time = 1;
343         break;
344       case_GETOPT_HELP_CHAR;
345       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
346       default:
347         usage (1);
348       }
349
350   n_args = argc - optind;
351
352   option_specified_date = ((datestr ? 1 : 0)
353                            + (batch_file ? 1 : 0)
354                            + (reference ? 1 : 0));
355
356   if (option_specified_date > 1)
357     {
358       error (0, 0,
359         _("the options to specify dates for printing are mutually exclusive"));
360       usage (1);
361     }
362
363   if (set_date && option_specified_date)
364     {
365       error (0, 0,
366           _("the options to print and set the time may not be used together"));
367       usage (1);
368     }
369
370   if (n_args > 1)
371     {
372       error (0, 0, _("too many non-option arguments"));
373       usage (1);
374     }
375
376   if ((set_date || option_specified_date)
377       && n_args == 1 && argv[optind][0] != '+')
378     {
379       error (0, 0, _("\
380 the argument `%s' lacks a leading `+';\n\
381 When using an option to specify date(s), any non-option\n\
382 argument must be a format string beginning with `+'."),
383              argv[optind]);
384       usage (1);
385     }
386
387   if (set_date)
388     datestr = set_datestr;
389
390   if (batch_file != NULL)
391     {
392       status = batch_convert (batch_file,
393                               (n_args == 1 ? argv[optind] + 1 : NULL));
394     }
395   else
396     {
397       status = 0;
398
399       if (!option_specified_date && !set_date)
400         {
401           if (n_args == 1 && argv[optind][0] != '+')
402             {
403               /* Prepare to set system clock to the specified date/time
404                  given in the POSIX-format.  */
405               set_date = 1;
406               datestr = argv[optind];
407               when = posixtime (datestr,
408                                 PDS_TRAILING_YEAR | PDS_CENTURY | PDS_SECONDS);
409               format = NULL;
410             }
411           else
412             {
413               /* Prepare to print the current date/time.  */
414               datestr = _("undefined");
415               time (&when);
416               format = (n_args == 1 ? argv[optind] + 1 : NULL);
417             }
418         }
419       else
420         {
421           /* (option_specified_date || set_date) */
422           if (reference != NULL)
423             {
424               if (stat (reference, &refstats))
425                 error (1, errno, "%s", reference);
426               when = refstats.st_mtime;
427             }
428           else
429             {
430               when = get_date (datestr, NULL);
431             }
432
433           format = (n_args == 1 ? argv[optind] + 1 : NULL);
434         }
435
436       if (when == -1)
437         error (1, 0, _("invalid date `%s'"), datestr);
438
439       if (set_date)
440         {
441           /* Set the system clock to the specified date, then regardless of
442              the success of that operation, format and print that date.  */
443           if (stime (&when) == -1)
444             {
445               error (0, errno, _("cannot set date"));
446               status = 1;
447             }
448         }
449
450       /* When given a universal time option, set TZ to UTC0 after
451          parsing the specified date, but before printing it.  */
452       MAYBE_SET_TZ_UTC0;
453
454       show_date (format, when);
455     }
456
457   close_stdout_status (2);
458
459   exit (status);
460 }
461
462 /* Display the date and/or time in WHEN according to the format specified
463    in FORMAT, followed by a newline.  If FORMAT is NULL, use the
464    standard output format (ctime style but with a timezone inserted). */
465
466 static void
467 show_date (const char *format, time_t when)
468 {
469   struct tm *tm;
470   char *out = NULL;
471   size_t out_length = 0;
472   /* ISO 8601 formats, in local and UTC.  See below regarding %z */
473   static char *iso_format_string[5][2] =
474   {
475     {"", ""},
476     {"%Y-%m-%d", "%Y-%m-%d"},
477     {"%Y-%m-%dT%H%z", "%Y-%m-%dT%HZ"},
478     {"%Y-%m-%dT%H:%M%z", "%Y-%m-%dT%H:%MZ"},
479     {"%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%SZ"}
480   };
481
482   tm = localtime (&when);
483
484   if (format == NULL)
485     {
486       /* Print the date in the default format.  Vanilla ANSI C strftime
487          doesn't support %e, but POSIX requires it.  If you don't use
488          a GNU strftime, make sure yours supports %e.
489          If you are not using GNU strftime, you want to change %z
490          in the RFC format to %Z; this gives, however, an invalid
491          RFC time format outside the continental United States and GMT. */
492
493       format = (rfc_format
494                 ? (universal_time
495                    ? "%a, %_d %b %Y %H:%M:%S GMT"
496                    : "%a, %_d %b %Y %H:%M:%S %z")
497                 : (iso_8601_format
498                    ? iso_format_string[iso_8601_format][universal_time]
499                    : "%a %b %e %H:%M:%S %Z %Y"));
500     }
501   else if (*format == '\0')
502     {
503       printf ("\n");
504       return;
505     }
506
507   do
508     {
509       out_length += 200;
510       out = (char *) xrealloc (out, out_length);
511
512       /* Mark the first byte of the buffer so we can detect the case
513          of strftime producing an empty string.  Otherwise, this loop
514          would not terminate when date was invoked like this
515          `LANG=de date +%p' on a system with good language support.  */
516       out[0] = '\1';
517     }
518   while (strftime (out, out_length, format, tm) == 0 && out[0] != '\0');
519
520   printf ("%s\n", out);
521   free (out);
522 }