date: use new libc date apis.

This commit is contained in:
Ori Bernstein 2020-08-10 19:01:45 -07:00
parent 9db78003db
commit 6d3a2e6531

View file

@ -1,101 +1,68 @@
#include <u.h> #include <u.h>
#include <libc.h> #include <libc.h>
static char *day[] = { enum {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", Nsec = 1000*1000*1000,
}; };
static char *mon[] = { void
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", usage(void)
"Aug", "Sep", "Oct", "Nov", "Dec"
};
int uflg, nflg, iflg, tflg, mflg;
char*
isodate(Tm *t)
{ {
static char c[26]; /* leave room to append isotime */ fprint(2, "usage: date [-itunm] [-f fmt] [seconds]\n");
snprint(c, 11, "%04d-%02d-%02d", exits("usage");
t->year + 1900, t->mon + 1, t->mday);
return c;
}
char*
isotime(Tm *t)
{
int tz;
char *c, *d;
d = isodate(t);
c = d+10;
snprint(c, 10, "T%02d:%02d:%02d",
t->hour, t->min, t->sec); /* append to isodate */
tz = t->tzoff / 60;
if(t->tzoff) {
/* localtime */
if (t->tzoff > 0) {
c[9] = '+';
} else {
c[9] = '-';
tz = -tz;
}
snprint(c+10, 6, "%02d:%02d", tz / 60, tz % 60);
} else {
c[9] = 'Z';
c[10] = 0;
}
return d;
}
char *
mailtime(Tm *t)
{
static char c[64];
char *sgn;
int off;
sgn = "+";
if(t->tzoff < 0)
sgn = "";
off = (t->tzoff/3600)*100 + (t->tzoff/60)%60;
snprint(c, sizeof(c), "%s, %.2d %s %.4d %.2d:%.2d:%.2d %s%.4d",
day[t->wday], t->mday, mon[t->mon], t->year + 1900,
t->hour, t->min, t->sec, sgn, off);
return c;
} }
void void
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
ulong now; int nflg, uflg;
Tm *tm; char *fmt;
vlong s, ns;
Tzone *tz;
Tm tm;
nflg = 0;
uflg = 0;
tz = nil;
fmt = "WW MMM _D hh:mm:ss ZZZ YYYY";
tmfmtinstall();
ARGBEGIN{ ARGBEGIN{
case 'n': nflg = 1; break; case 'n': nflg = 1; break;
case 'u': uflg = 1; break; case 'u': uflg = 1; break;
case 't': tflg = 1; /* implies -i */ case 't': fmt = "YYYY-MM-DDThh:mm:ssZZ"; break;
case 'i': iflg = 1; break; case 'i': fmt = "YYYY-MM-DD"; break;
case 'm': mflg = 1; break; case 'm': fmt = "WW, DD MMM YYYY hh:mm:ss Z"; break;
default: fprint(2, "usage: date [-itunm] [seconds]\n"); exits("usage"); case 'f': fmt = EARGF(usage()); break;
default: usage();
}ARGEND }ARGEND
if(argc == 1) s = 0;
now = strtoul(*argv, 0, 0); ns = 0;
else switch(argc) {
now = time(0); case 0:
ns = nsec();
s = ns/Nsec;
ns = ns%Nsec;
break;
case 1:
s = strtoll(argv[0], nil, 0);
ns = 0;
break;
default:
usage();
break;
}
if(!uflg && (tz = tzload("local")) == nil)
sysfatal("timezone: %r");
if(tmtimens(&tm, s, ns, tz) == nil)
sysfatal("now: %r");
if(nflg) if(nflg)
print("%ld\n", now); print("%lld\n", tmnorm(&tm));
else { else
tm = uflg ? gmtime(now) : localtime(now); if(print("\n", tmfmt(&tm, fmt)) == -1)
if(iflg) { sysfatal("%r");
if(tflg)
print("%s\n", isotime(tm));
else
print("%s\n", isodate(tm));
} else if(mflg)
print("%s\n", mailtime(tm));
else
print("%s", asctime(tm));
}
exits(0); exits(0);
} }