Live video on the AT Protocol
1package aqtime
2
3import (
4 "fmt"
5 "regexp"
6 "strings"
7 "time"
8)
9
10var RE *regexp.Regexp
11var Pattern string = `^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d)(?:[:-])(\d\d)(?:[:-])(\d\d)(?:[.-])(\d\d\d)Z$`
12
13type AQTime string
14
15func init() {
16 RE = regexp.MustCompile(fmt.Sprintf(`^%s$`, Pattern))
17}
18
19var fstr = "2006-01-02T15:04:05.000Z"
20
21// return a consistently formatted timestamp
22func FromMillis(ms int64) AQTime {
23 return AQTime(time.UnixMilli(ms).UTC().Format(fstr))
24}
25
26// return a consistently formatted timestamp
27func FromSec(sec int64) AQTime {
28 return AQTime(time.Unix(sec, 0).UTC().Format(fstr))
29}
30
31func FromString(str string) (AQTime, error) {
32 bits := RE.FindStringSubmatch(str)
33 if bits == nil {
34 return "", fmt.Errorf("bad time format, expected=%s got=%s", fstr, str)
35 }
36 return AQTime(str), nil
37}
38
39func FromTime(t time.Time) AQTime {
40 return AQTime(t.UTC().Format(fstr))
41}
42
43// year, month, day, hour, min, sec, millisecond
44func (aqt AQTime) Parts() (string, string, string, string, string, string, string) {
45 bits := RE.FindStringSubmatch(aqt.String())
46 return bits[1], bits[2], bits[3], bits[4], bits[5], bits[6], bits[7]
47}
48
49func (aqt AQTime) String() string {
50 return string(aqt)
51}
52
53// version of AQTime suitable for saving as a file (esp on windows)
54func (aqt AQTime) FileSafeString() string {
55 str := string(aqt)
56 str = strings.ReplaceAll(str, ":", "-")
57 str = strings.ReplaceAll(str, ".", "-")
58 return str
59}
60
61func (aqt AQTime) Time() time.Time {
62 t, err := time.Parse(fstr, aqt.String())
63 if err != nil {
64 panic(err)
65 }
66 return t
67}