Add -u option to date (POSIX and Plan 9, and useful)

This commit is contained in:
Robert Ransom 2012-04-23 08:32:24 -07:00
parent 3863ccdf98
commit c018f86fc7
2 changed files with 13 additions and 3 deletions

4
date.1
View File

@ -5,6 +5,7 @@ date \- print date and time
.B date .B date
.RB [ \-d .RB [ \-d
.IR time ] .IR time ]
.RB [ \-u ]
.RI [+ format ] .RI [+ format ]
.SH DESCRIPTION .SH DESCRIPTION
.B date .B date
@ -18,5 +19,8 @@ is given it is used to format the date as per
prints prints
.I time .I time
instead of the system time, given as the number of seconds since the Unix epoch. instead of the system time, given as the number of seconds since the Unix epoch.
.TP
.B \-u
prints UTC time instead of local time.
.SH SEE ALSO .SH SEE ALSO
.IR strftime (3) .IR strftime (3)

12
date.c
View File

@ -11,21 +11,27 @@ main(int argc, char *argv[])
char buf[BUFSIZ], c; char buf[BUFSIZ], c;
char *fmt = "%c"; char *fmt = "%c";
struct tm *now = NULL; struct tm *now = NULL;
struct tm *(*tztime)(const time_t *) = localtime;
const char *tz = "local";
time_t t; time_t t;
t = time(NULL); t = time(NULL);
while((c = getopt(argc, argv, "d:")) != -1) while((c = getopt(argc, argv, "d:u")) != -1)
switch(c) { switch(c) {
case 'd': case 'd':
t = estrtol(optarg, 0); t = estrtol(optarg, 0);
break; break;
case 'u':
tztime = gmtime;
tz = "gm";
break;
default: default:
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if(optind < argc && argv[optind][0] == '+') if(optind < argc && argv[optind][0] == '+')
fmt = &argv[optind][1]; fmt = &argv[optind][1];
if(!(now = localtime(&t))) if(!(now = tztime(&t)))
eprintf("localtime failed\n"); eprintf("%stime failed\n", tz);
strftime(buf, sizeof buf, fmt, now); strftime(buf, sizeof buf, fmt, now);
puts(buf); puts(buf);