func GetTimeDifference() string {
nowTime := time.Now()
// 当天秒级时间戳
nowTimeStamp := nowTime.Unix()
nowTimeStr := nowTime.Format("2006-01-02")
//使用Parse 默认获取为UTC时区 需要获取本地时区 所以使用ParseInLocation
t2, _ := time.ParseInLocation("2006-01-02", nowTimeStr, time.Local)
// 第二天零点时间戳
towTimeStamp := t2.AddDate(0, 0, 1).Unix()
return strconv.FormatInt(towTimeStamp - nowTimeStamp, 10)
}
addTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
timeSamp := addTime.Unix()
fmt.Println(timeSamp) // 1649952000
t := time.Now()
addTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
timeStr := addTime.Format("2006-01-02")
fmt.Println(timeStr) // 2022-04-15
ts := time.Now().AddDate(0, 0, -1)
timeYesterday := time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, ts.Location())
timeStampYesterday := timeYesterday.Unix()
fmt.Println(timeStampYesterday) // 1649865600
ts := time.Now().AddDate(0, 0, -1)
timeYesterday := time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, ts.Location()).Unix()
timeStr := time.Unix(timeYesterday, 0).Format("2006-01-02")
fmt.Println(timeStr) // 2022-04-14
或者
ts := time.Now().AddDate(0, 0, -1)
timeYesterday := time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, ts.Location())
timeStr := timeYesterday.Format("2006-01-02")
fmt.Println(timeStr) // 2022-04-14
例子1:
过去某天,如 2022-02-28 第二天0点整:2022-03-01 00:00:00
nowTimeStr := "2022-02-28"
//使用Parse 默认获取为UTC时区 需要获取本地时区 所以使用ParseInLocation
t2, _ := time.ParseInLocation("2006-01-02", nowTimeStr, time.Local)
towTimeStamp := t2.AddDate(0, 0, 1).Unix()
towTimeStr := time.Unix(towTimeStamp, 0).Format("2006-01-02 15:04:05")
fmt.Println(towTimeStr) // 2022-03-01 00:00:00
例子2:
未来某天,如 2022-04-30 第二天0点整:2022-05-01
nowTimeStr := "2022-04-30"
//使用Parse 默认获取为UTC时区 需要获取本地时区 所以使用ParseInLocation
t2, _ := time.ParseInLocation("2006-01-02", nowTimeStr, time.Local)
towTimeStamp := t2.AddDate(0, 0, 1).Unix()
towTimeStr := time.Unix(towTimeStamp, 0).Format("2006-01-02")
fmt.Println(towTimeStr) // 2022-05-01
2022-04-01 前一天0点整:2022-03-31 00:00:00
nowTimeStr := "2022-04-01"
//使用Parse 默认获取为UTC时区 需要获取本地时区 所以使用ParseInLocation
t2, _ := time.ParseInLocation("2006-01-02", nowTimeStr, time.Local)
towTimeStamp := t2.AddDate(0, 0, -1).Unix()
towTimeStr := time.Unix(towTimeStamp, 0).Format("2006-01-02 15:04:05")
fmt.Println(towTimeStr) // 2022-03-31 00:00:00