usage: strptime fmt timestamp Most other userspace implementations allow in date(1) the parsing of dates. That way, one can use a date string, and manipulate it in scripts. However, the current date(1) implementation only accepts Unix epochs to describe date and time. Rather than patching date(1), I decided to make it a different tool, which, I believe, is closer to the Unix philosophy. --- .gitignore | 1 + Makefile | 1 + README | 1 + strptime.1 | 22 ++++++++++++++++++++++ strptime.c | 38 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 63 insertions(+) create mode 100644 strptime.1 create mode 100644 strptime.c
diff --git a/.gitignore b/.gitignore index daa7189..e591886 100644 --- a/.gitignore +++ b/.gitignore @@ -76,6 +76,7 @@ /split /sponge /strings +/strptime /sync /tac /tail diff --git a/Makefile b/Makefile index 8a4c1ef..55e00d9 100644 --- a/Makefile +++ b/Makefile @@ -165,6 +165,7 @@ BIN =\ split\ sponge\ strings\ + strptime\ sync\ tac\ tail\ diff --git a/README b/README index f16eab8..91a60f9 100644 --- a/README +++ b/README @@ -117,6 +117,7 @@ The following tools are implemented: 0=*|o split . 0=*|x sponge . 0#*|o strings . +0=* x strptime . 0=*|x sync . 0=* x tac . 0=*|o tail . diff --git a/strptime.1 b/strptime.1 new file mode 100644 index 0000000..8f91238 --- /dev/null +++ b/strptime.1 @@ -0,0 +1,22 @@ +.Dd 2024-02-25 +.Dt STRPTIME 1 +.Os sbase +.Sh NAME +.Nm strptime +.Nd parse date and time string +.Sh SYNOPSIS +.Nm +.Ar time format +.Sh DESCRIPTION +.Nm +parses +.Ar time +according to +.Ar format +(see +.Xr strptime 3 ) . +and prints it as the number of seconds since the +Unix epoch. +.Sh SEE ALSO +.Xr date 1 , +.Xr strptime 3 diff --git a/strptime.c b/strptime.c new file mode 100644 index 0000000..381a804 --- /dev/null +++ b/strptime.c @@ -0,0 +1,38 @@ +#include <stdio.h> +#include <time.h> + +#include "util.h" + +static void +usage(void) +{ + eprintf("usage: %s format time\n", argv0); +} + +int +main(int argc, char *argv[]) +{ + struct tm tm; + time_t time; + char *fmt; + + ARGBEGIN { + default: + usage(); + } ARGEND + + /* This make mktime(3) guess whether Daylight Saving Time is in effect. + * If not specified, the output is non-deterministic, considering that + * tm is initially random */ + tm.tm_isdst = -1; + + if (argc != 2) + usage(); + if (strptime(argv[1], argv[0], &tm) == NULL) + eprintf("unable to parse\n"); + if ((time = mktime(&tm)) == -1) + eprintf("mktime:"); + + printf("%ld\n", time); + return 0; +} -- 2.43.0