-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvtime.go
98 lines (80 loc) · 1.59 KB
/
vtime.go
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
package vtime
import (
"time"
"v8.run/go/vtime/internal/parse"
)
type WallClock struct{}
type Parseable interface {
time.Time | int64 | uint64 | string | WallClock
}
type Time struct {
Unix int64
Nano int64
TZ *time.Location
}
func ft(t time.Time) Time {
unix := t.Unix()
nano := t.Nanosecond()
return Time{Unix: unix, Nano: int64(nano), TZ: t.Location()}
}
func tt(v Time) time.Time {
if v.TZ == nil {
v.TZ = time.Local
}
return time.Unix(int64(v.Unix), int64(v.Nano)).In(v.TZ)
}
func Now() Time {
now := time.Now()
return ft(now)
}
func VTime[T Parseable](t ...T) Time {
if len(t) <= 0 {
return Now() // IF NO ARGUMENTS ARE PASSED, RETURN CURRENT TIME
}
switch v := any(&t[0]).(type) {
case *time.Time:
return ft(*v)
case *int64: // UNIX TIME MILLISECONDS
return UnixMilli(*v)
case *uint64: // UNIX TIME MILLISECONDS
return UnixMilli(int64(*v))
case *string:
if len(t) == 1 {
unix, nano, _ := parse.Parse8601(*v)
return Time{Unix: unix, Nano: nano, TZ: time.Local}
} else {
// TODO: Support custom time formats
return Now()
}
case *WallClock:
return Now()
}
// Default to Now()
return Now()
}
func UTC[T Parseable](t ...T) Time {
return VTime(t...).UTC()
}
// January=1...December=12
type Month = time.Month
func (v Time) Time() time.Time {
return tt(v)
}
func (v Time) In(tz *time.Location) Time {
if tz == nil {
tz = time.Local
}
v.TZ = tz
return v
}
func (v Time) UTC() Time {
v.TZ = time.UTC
return v
}
func (v Time) Local() Time {
v.TZ = time.Local
return v
}
func (v Time) String() string {
return tt(v).Format(time.RFC3339Nano)
}