1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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;
}
|