summaryrefslogtreecommitdiff
path: root/sys/src/cmd/seconds.c
blob: c30330ede6da70867f5d0c953a3c9e10cace6f5d (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <u.h>
#include <libc.h>
#include <ctype.h>

char *knownfmt[] = {
	/* asctime */
	"WW MMM DD hh:mm:ss ?Z YYYY",
	/* RFC3339 */
	"YYYY-MM-DD[T]hh:mm:ss[Z]?Z",
	"YYYY-MM-DD[T]hh:mm:ss[Z]?Z",
	"YYYY-MM-DD[T]hh:mm:ss ?Z",
	"YYYY-MM-DD[T]hh:mm:ss?Z",
	nil,
};

char *datefmt[] = {
	/* RFC5322 */
	"?W ?DD ?MMM ?YYYY",
	"?W, DD-?MM-YY",
	/* RFC822/RFC2822 */
	"DD MMM YYYY",
	"DD MMM YY",
	/* RFC850 */
	"WW, DD-MMM-YY",
	/* RFC1123 */
	"WWW, DD MMM YYYY",
	/* RFC 3339 and human-readable variants */
	"YYYY-MM-DD",
	"YYYY-MM-DD [@] ",
	/* random formats */
	"?W ?MMM ?DD ?YYYY",
	"?MMM ?DD ?YYYY",
	"?DD ?MM ?YYYY",
	"MMM ?DD ?YYYY",
	"YYYY ?MM ?DD",
	"YYYY ?DD ?MM",
	"YYYY/MM?/DD?",
	"MMM YYYY ?DD",
	"?DD YYYY MMM",
	"MM/DD/YYYY",
	nil
};

char *timefmt[] = {
	" hh:mm:ss",
	" hh:mm",
	" hh",
	" hh:mm:ss ?A",
	" hh:mm ?A",
	" hh ?A",
	"",
	nil,
};

char *zonefmt[] = {
	" ?Z",
	"",
	nil,
};

static int
nojunk(char *p)
{
	while(isspace(*p))
		p++;
	if(*p == '\0')
		return 1;
	werrstr("trailing junk");
	return 0;
}

static void
usage(void)
{
	fprint(2, "usage: %s [-f fmt] date-time...\n", argv0);
	exits("usage");
}

/*
 * seconds absolute_date ... - convert absolute_date to seconds since epoch
 */
void
main(int argc, char **argv)
{
	char **f, **df, **tf, **zf, *fmt, *ep, buf[256];
	Tzone *tz;
	Tm tm;
	int i;

	fmt = nil;
	ARGBEGIN{
	case 'f':
		fmt = EARGF(usage());
		break;
	default:
		usage();
	}ARGEND;

	if((tz = tzload("local")) == nil)
		sysfatal("bad local time: %r");
	for(i = 0; i < argc; i++){
		if(fmt != nil){
			if(tmparse(&tm, fmt, argv[i], tz, &ep) && nojunk(ep))
				goto Found;
		}else{
			for(f = knownfmt; *f != nil; f++)
				if(tmparse(&tm, *f, argv[i], tz, &ep) != nil && nojunk(ep))
					goto Found;
			for(df = datefmt; *df; df++)
			for(tf = timefmt; *tf; tf++)
			for(zf = zonefmt; *zf; zf++){
				snprint(buf, sizeof(buf), "%s%s%s", *df, *tf, *zf);
				if(tmparse(&tm, buf, argv[i], tz, &ep) != nil && nojunk(ep))
					goto Found;
			}
		}
		sysfatal("tmparse: %r");
Found:
		print("%lld\n", tmnorm(&tm));
	}
	exits(nil);
}