Skip to content

Commit 810d3ee

Browse files
authored
Merge pull request #448 from Leif160519/dev
重写GetTimeDuration方法,将持续时间为开始时间与当前时间的间隔改为开始时间和结束时间的间隔(默认)
2 parents 6d8f4c1 + 686de23 commit 810d3ee

File tree

1 file changed

+36
-14
lines changed

1 file changed

+36
-14
lines changed

controllers/public.go

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,24 +42,46 @@ func GetTime(timeStr interface{}, timeFormat ...string) string {
4242
}
4343

4444
// 转换时间为持续时长
45-
func GetTimeDuration(date string) string {
45+
func GetTimeDuration(startTime string,endTime string) string {
4646
var tm = "N/A"
47-
if date != "" {
48-
T1 := date[0:10]
49-
T2 := date[11:19]
50-
T3 := T1 + " " + T2
51-
tm2, _ := time.Parse("2006-01-02 15:04:05", T3)
52-
sub := time.Now().UTC().Sub(tm2.UTC())
47+
if startTime != "" && endTime != "" {
48+
starT1 := startTime[0:10]
49+
starT2 := startTime[11:19]
50+
starT3 := starT1 + " " + starT2
51+
startm2, err := time.Parse("2006-01-02 15:04:05", starT3)
52+
if err != nil {
53+
return tm // 如果解析失败,则返回N/A
54+
}
55+
56+
endT1 := endTime[0:10]
57+
endT2 := endTime[11:19]
58+
endT3 := endT1 + " " + endT2
59+
endm2, err := time.Parse("2006-01-02 15:04:05", endT3)
60+
if err != nil {
61+
return tm // 如果解析失败,则返回N/A
62+
}
63+
64+
sub := endm2.UTC().Sub(startm2.UTC())
5365

5466
t := int64(sub.Seconds())
55-
if t > 86400 {
56-
tm = fmt.Sprintf("%dd%dh", t/86400, t%86400/3600)
57-
} else if t > 3600 {
58-
tm = fmt.Sprintf("%dh%dm", t/3600, t%3600/60)
59-
} else if t > 60 {
60-
tm = fmt.Sprintf("%dh%dm", t/60, t%60)
67+
if t >= 86400 {
68+
days := t / 86400
69+
hours := (t % 86400) / 3600
70+
tm = fmt.Sprintf("%dd%dh", days, hours)
6171
} else {
62-
tm = fmt.Sprintf("%ds", t)
72+
hours := t / 3600
73+
minutes := (t % 3600) / 60
74+
if hours > 0 {
75+
tm = fmt.Sprintf("%dh%dm", hours, minutes)
76+
} else {
77+
// 如果小时为0,则只显示分钟和秒
78+
seconds := t % 60
79+
tm = fmt.Sprintf("%dm%ds", minutes, seconds)
80+
if minutes == 0 {
81+
// 如果分钟也为0,则只显示秒
82+
tm = fmt.Sprintf("%ds", seconds)
83+
}
84+
}
6385
}
6486
}
6587
return tm

0 commit comments

Comments
 (0)