-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
75 lines (73 loc) · 1.46 KB
/
time.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
package copier
import (
"database/sql/driver"
"fmt"
"reflect"
"time"
)
func copyTime(dst reflect.Value, src reflect.Value) (err error) {
if src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
return
}
switch src.Kind() {
case reflect.String:
v := src.String()
if v == "" {
return
}
t, parseErr := time.Parse(time.RFC3339, v)
if parseErr != nil {
err = parseErr
return
}
dst.Set(reflect.ValueOf(t))
break
case reflect.Int, reflect.Int32, reflect.Int64:
v := src.Int()
if v < 1 {
return
}
t := time.UnixMilli(v)
dst.Set(reflect.ValueOf(t))
break
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v := src.Uint()
if v < 1 {
return
}
t := time.UnixMilli(int64(v))
dst.Set(reflect.ValueOf(t))
break
case reflect.Struct:
// time
if src.Type().ConvertibleTo(timeType) {
v := src.Interface().(time.Time)
dst.SetString(v.Format(time.RFC3339))
return
}
// sql
if src.Type().Implements(sqlValuerType) {
v := src.Interface().(driver.Valuer)
value, valueErr := v.Value()
if valueErr != nil {
err = valueErr
return
}
if value == nil {
return
}
err = copyTime(dst, reflect.ValueOf(value))
return
}
err = fmt.Errorf("copier: time not support %s source type", src.Type().String())
break
case reflect.Ptr:
err = copyTime(dst, src.Elem())
break
default:
err = fmt.Errorf("copier: time not support %s source type", src.Type().String())
return
}
return
}