-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
107 lines (90 loc) · 2.06 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package do
import (
"time"
)
const (
DateTimeFormat = "2006-01-02 15:04:05"
DateFormat = "2006-01-02"
)
var (
Location = time.FixedZone("CST", 8*3600) // 东八,Asia/Shanghai
)
// IsExpired show if deadline is expired compared to now
// always return false if deadline is zero
func IsExpired(deadline, now time.Time) bool {
if deadline.IsZero() {
return false
}
return !deadline.After(now)
}
func TodayZero() time.Time {
now := time.Now()
return DayZero(now)
}
func ThisMonthFirst() time.Time {
now := time.Now()
return MonthFirst(now)
}
func ThisYearFirst() time.Time {
now := time.Now()
return YearFirst(now)
}
func DayZero(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, t.Location())
}
func MonthFirst(t time.Time) time.Time {
y, m, _ := t.Date()
return time.Date(y, m, 1, 0, 0, 0, 0, t.Location())
}
func YearFirst(t time.Time) time.Time {
y, _, _ := t.Date()
return time.Date(y, 1, 1, 0, 0, 0, 0, t.Location())
}
// ParseTime parse time string t with layout s one by one; if layouts is empty, it will use "2006-01-02 15:04:05" as default
func ParseTime(t string, layouts ...string) (r time.Time, err error) {
if len(layouts) == 0 {
layouts = append(layouts, "2006-01-02 15:04:05")
}
for _, layout := range layouts {
r, err = time.ParseInLocation(layout, t, time.Local)
if err == nil {
return
}
}
return
}
// AgeByBirth get age and unit by birthday. It will use time.Now() if not input now.
// If exist year, ignore month and day; If exist month, ignore day.
func AgeByBirth(birthday time.Time, now ...time.Time) (age int, unit string) {
var nt time.Time
if len(now) == 0 {
nt = time.Now()
} else {
nt = now[0]
}
// 拿到时间间隔
bd := nt.Sub(birthday)
if bd < 0 {
return
}
if bd == 0 {
age = 1
unit = "天"
}
zero := time.Time{}
ny, nm, nd := zero.Date() // 1 1 1
y, m, d := zero.Add(bd).Date()
ry, rm, rd := y-ny, m-nm, d-nd
if ry > 0 {
age = ry
unit = "岁"
} else if rm > 0 {
age = int(rm)
unit = "月"
} else if rd > 0 {
age = rd
unit = "天"
}
return
}