Skip to content

Commit 18782d1

Browse files
authored
Merge pull request #480 from Echo21bash/Echo21bash-patch-1
重写GetCSTtime函数,支持任意时区转换到CST
2 parents f802dd3 + 97ee483 commit 18782d1

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

controllers/public.go

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -87,20 +87,38 @@ func GetTimeDuration(startTime string,endTime string) string {
8787
return tm
8888
}
8989

90-
// 转换UTC时区到CST
90+
// 转换任意时区到CST
9191
func GetCSTtime(date string) string {
92-
var tm string
93-
tm = time.Now().Format("2006-01-02 15:04:05")
94-
if date != "" {
95-
T1 := date[0:10]
96-
T2 := date[11:19]
97-
T3 := T1 + " " + T2
98-
tm2, _ := time.Parse("2006-01-02 15:04:05", T3)
99-
h, _ := time.ParseDuration("-1h")
100-
tm3 := tm2.Add(-8 * h)
101-
tm = tm3.Format("2006-01-02 15:04:05")
92+
var t time.Time
93+
if date == "" {
94+
// 获取当前时间并转换为 CST
95+
t = time.Now().In(cstLoc)
96+
} else {
97+
parsedTime, err := parseDate(date)
98+
if err != nil {
99+
// 处理错误,例如返回空字符串或日志记录
100+
return ""
101+
}
102+
// 转换为 CST 时区
103+
t = parsedTime.In(cstLoc)
102104
}
103-
return tm
105+
return t.Format("2006-01-02 15:04:05")
106+
}
107+
108+
// 解析日期字符串,支持带时区和固定格式
109+
func parseDate(date string) (time.Time, error) {
110+
// 尝试常见带时区的格式(如 RFC3339)
111+
t, err := time.Parse(time.RFC3339, date)
112+
if err == nil {
113+
return t, nil
114+
}
115+
// 尝试无时区格式,假设为 UTC
116+
t, err = time.ParseInLocation("2006-01-02 15:04:05", date, time.UTC)
117+
if err == nil {
118+
return t, nil
119+
}
120+
// 可根据需要添加更多格式
121+
return time.Time{}, fmt.Errorf("无法解析时间:%s", date)
104122
}
105123

106124
func TimeFormat(timestr, format string) string {

0 commit comments

Comments
 (0)