问题
开发时经常遇到求时间的差值,比如2019/05/05和2019/04/27日的差值是多少,相差多少天?
time包
func GetTimeArr(start, end string) int64{
timeLayout := "2006/01/02"
loc, _ := time.LoadLocation("Local")
// 转成时间戳
startUnix := time.ParseInLocation(timeLayout, start, loc)
endUnix := time.ParseInLocation(timeLayout, end, loc)
startTime := startUnix.Unix()
endTime := endUnix.Unix()
// 求相差天数
date := (endTime - startTime) / 86400
return date
}
- 先把字符串转成时间戳,要注意的是2019/04/27,上面timeLayout 的分隔也要是/,也可以换成 - 但是两个要同步
- 求结束时间和开始时间的差值
- 一天是86400, 差值减去后除一下就行
转成字符串
接着上面的优化一下,把时间戳在转回来,转成字符串表示
func GetTimeArr(start, end string) []string{
timeLayout := "2006/01/02"
loc, _ := time.LoadLocation("Local")
// 转成时间戳
startUnix := time.ParseInLoc