summaryrefslogtreecommitdiffstats
path: root/src/datetime.c
diff options
context:
space:
mode:
authorP. J. McDermott <pj@pehjota.net>2021-08-28 17:53:27 (EDT)
committer P. J. McDermott <pj@pehjota.net>2021-08-29 12:40:53 (EDT)
commit28226fed7a52114efbd43860ef1ff7794ce88931 (patch)
tree537214f4e2bab9c9a4136380a272733835b6361a /src/datetime.c
parent21e7e051b8c14d764bb283da59d8c04fb336ed77 (diff)
downloadatsign-28226fed7a52114efbd43860ef1ff7794ce88931.zip
atsign-28226fed7a52114efbd43860ef1ff7794ce88931.tar.gz
atsign-28226fed7a52114efbd43860ef1ff7794ce88931.tar.bz2
datetime: WIP
Diffstat (limited to 'src/datetime.c')
-rw-r--r--src/datetime.c104
1 files changed, 104 insertions, 0 deletions
diff --git a/src/datetime.c b/src/datetime.c
new file mode 100644
index 0000000..f39f80c
--- /dev/null
+++ b/src/datetime.c
@@ -0,0 +1,104 @@
+#define _XOPEN_SOURCE
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "datetime.h"
+
+static const char *DATETIME_FMTS_[] = {
+ "%H:%M:%S",
+ "%I:%M:%S %p",
+ "%H:%M",
+ "%Y-%m-%dT%H:%M:%S",
+ "%Y-%m-%d %H:%M:%S",
+ "%A %B %d, %Y %H:%M:%S",
+ NULL
+};
+
+static char *
+datetime_normalize_spacing(int argc, const char *argv[])
+{
+ int buf_l;
+ int i;
+ int l;
+ bool was_space;
+ int j;
+ char *buf;
+ int buf_i;
+
+ buf_l = 0;
+ for (i = 0; i < argc; ++i) {
+ l = strlen(argv[i]);
+ was_space = true;
+ for (j = 0; j < l; ++j) {
+ if (isspace(argv[i][j]) != 0) {
+ if (was_space == false) {
+ buf_l++;
+ was_space = true;
+ }
+ } else {
+ buf_l++;
+ was_space = false;
+ }
+ }
+ ++buf_l;
+ }
+
+ buf = calloc(buf_l, sizeof(*buf));
+ if (buf == NULL) {
+ fprintf(stderr, "Failed to allocate buffer: %s\n",
+ strerror(errno));
+ return NULL;
+ }
+
+ buf_i = 0;
+ for (i = 0; i < argc; ++i) {
+ l = strlen(argv[i]);
+ was_space = true;
+ for (j = 0; j < l; ++j) {
+ if (isspace(argv[i][j]) != 0) {
+ if (was_space == false) {
+ buf[buf_i++] = ' ';
+ was_space = true;
+ }
+ } else {
+ buf[buf_i++] = argv[i][j];
+ was_space = false;
+ }
+ }
+ buf[buf_i++] = ' ';
+ }
+ buf[--buf_i] = '\0';
+
+ return buf;
+}
+
+int
+datetime_parse(int argc, const char *argv[], struct tm *tm)
+{
+ int e = -1;
+ char *buf;
+ int i;
+ char *end;
+
+ buf = datetime_normalize_spacing(argc, argv);
+ if (buf == NULL) {
+ return -1;
+ }
+
+ for (i = 0; DATETIME_FMTS_[i] != NULL; ++i) {
+ printf("%s =~ %s\n", buf, DATETIME_FMTS_[i]);
+ end = strptime(buf, DATETIME_FMTS_[i], tm);
+ if (end != NULL && *end == '\0') {
+ e = 0;
+ break;
+ }
+ }
+
+ free(buf);
+ return e;
+}