v / vlib / time / json_custom.c.v
41 lines · 35 sloc · 1012 bytes · bae7684276f5e56a9293a38bb286df3644157109
Raw
1module time
2
3// from_json_string implements a custom decoder for json2 (unix)
4pub fn (mut t Time) from_json_number(raw_number string) ! {
5 t = unix(raw_number.i64())
6}
7
8// from_json_string implements a custom decoder for json2 (iso8601/rfc3339/unix)
9pub fn (mut t Time) from_json_string(raw_string string) ! {
10 is_iso8601 := raw_string[4] == `-` && raw_string[7] == `-`
11 if is_iso8601 {
12 t = parse_iso8601(raw_string)!
13 return
14 }
15
16 is_rfc3339 := raw_string.len == 24 && raw_string[23] == `Z` && raw_string[10] == `T`
17 if is_rfc3339 {
18 t = parse_rfc3339(raw_string)!
19 return
20 }
21
22 mut is_unix_timestamp := true
23 for c in raw_string {
24 if c == `-` || (c >= `0` && c <= `9`) {
25 continue
26 }
27 is_unix_timestamp = false
28 break
29 }
30 if is_unix_timestamp {
31 t = unix(raw_string.i64())
32 return
33 }
34
35 return error('Expected iso8601/rfc3339/unix time but got: ${raw_string}')
36}
37
38// to_json implements a custom encoder for json2 (rfc3339)
39pub fn (t Time) to_json() string {
40 return '"' + t.format_rfc3339() + '"'
41}
42