-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.go
56 lines (49 loc) · 1.01 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
package go_trellis_db
import (
"database/sql"
"strings"
"time"
)
func LaravelNow() LaravelNullTime {
return LaravelNullTime{Time: time.Now(), Valid: true}
}
const LARAVEL_FORMAT = "2006-01-02 15:04:05"
type LaravelNullTime sql.NullTime
func (t *LaravelNullTime) Scan(val interface{}) (err error) {
if val == nil {
t.Valid = false
return
}
s := string(val.([]byte))
if strings.HasPrefix(s, "0000") {
t.Valid = false
return
}
t.Time, err = time.Parse(LARAVEL_FORMAT, s)
t.Valid = err == nil
return
}
func (t *LaravelNullTime) UnmarshalJSON(d []byte) (err error) {
if d == nil {
t.Valid = false
return
}
s := strings.ReplaceAll(string(d), `"`, "")
if s == "null" {
t.Valid = false
return
}
if strings.HasPrefix(s, "0001") {
t.Valid = false
return
}
t.Time, err = time.Parse(LARAVEL_FORMAT, s)
t.Valid = err == nil
return
}
func (t LaravelNullTime) MarshalJSON() ([]byte, error) {
if !t.Valid {
return []byte("null"), nil
}
return []byte(`"` + t.Time.Format(LARAVEL_FORMAT) + `"`), nil
}