昨天遇到一个问题,在完成时间转换时间戳,在后续测试中发现转换后的时间戳转成时间后,时间发生错误,时间和转换时间不一致问题
如下:
package main
import (
"fmt"
"time"
)
func main() {
Start := "2024-08-07 14:15:13"
End := "2024-08-08 14:15:13"
Layout := "2006-01-02 15:04:05" // 格式
StartTime, err := time.Parse(Layout, Start)
if err != nil {
return
}
EndTime, err := time.Parse(Layout, End)
if err != nil {
return
}
duration := EndTime.Sub(StartTime)
Hours := uint(duration.Hours())
// 获取Unix时间戳(秒)
Startstamp := StartTime.Unix()
Endstamp := EndTime.Unix()
msg := fmt.Sprintf("hours: %d, start: %d, end: %d", Hours, Startstamp, Endstamp)
print(msg)
}
结果:hours: 24, start: 1723040113, end: 1723126513
time.Parse函数可以用来将时间字符串按照指定的布局解析成time.Time类型,但是它默认使用UTC时区,所以转换成时间戳在转成时间和实际相差8小时,需要 time.LoadLocation设置时区,如下:
package main
import (
"fmt"
"time"
)
func main() {
Start := "2024-08-07 14:15:13"
End := "2024-08-08 14:15:13"
Layout := "2006-01-02 15:04:05" // 格式
locationName := "Asia/Shanghai"
// 根据时区名称加载时区
location, err := time.LoadLocation(locationName)
if err != nil {
fmt.Println("时区加载失败:", err)
return
}
StartTime, err := time.ParseInLocation(Layout, Start, location)
if err != nil {
return
}
EndTime, err := time.ParseInLocation(Layout, End, location)
if err != nil {
return
}
duration := EndTime.Sub(StartTime)
Hours := uint(duration.Hours())
// 获取Unix时间戳(秒)
Startstamp := StartTime.Unix()
Endstamp := EndTime.Unix()
msg := fmt.Sprintf("hours: %d, start: %d, end: %d", Hours, Startstamp, Endstamp)
print(msg)
}
结果: hours: 24, start: 1723011313, end: 1723097713