我在进行日期比较时遇到问题。
代码:
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func checkTime(date string) { //Note that the date passed here is from SQL Server
formattedDate, err := time.Parse("2006-01-02 15:04:05", date)
if err != nil {
log.Print(err)
return
}
now := time.Now()
later := now.Add(1 * time.Hour) // 1 hour later than now
log.Print("Now : ", now.Format("2006-01-02 15:04:05"))
log.Print("Given : ", formattedDate.Format("2006-01-02 15:04:05"))
log.Print("Later : ", later.Format("2006-01-02 15:04:05"))
if inTimeSpan(now, later, formattedDate) {
log.Print("Date is in the range.")
} else if formattedDate.After(later) {
log.Print("Date is not in the range. Later than 1 hour after now.")
} else {
log.Print("Date is not in the range. Before now")
}
return
}
预期输出:
2019/12/15 19:31:02 Now : 2019-12-15 19:31:02
2019/12/15 19:31:02 Given : 2019-12-15 19:45:00
2019/12/15 19:31:02 Later : 2019-12-15 20:31:02
2019/12/15 19:31:02 Date is in the range.
实际输出:
2019/12/15 19:31:02 Now : 2019-12-15 19:31:02
2019/12/15 19:31:02 Given : 2019-12-15 19:45:00
2019/12/15 19:31:02 Later : 2019-12-15 20:31:02
2019/12/15 19:31:02 Date is not in the range. Later than 1 hour after now.
由于某种原因,日期比较工作正常。有什么我想念的吗?
答案 0 :(得分:0)
阿德里安(答案):
可能想将时区添加到调试打印语句中。我的猜测是那些时间并非全部都在同一TZ。 –阿德里安
SQL Server将时区默认为UTC,其余时间为+0200
。我最终对SQL Server进行了一些大的更改,以将所有日期设置为+0200
,并将所有新日期设置为正确的时区。