golang中计算时间相差天数大多使用除以24小时,这种方法存在问题,存在按天数明明相差了4天,实际计算出来只有3天的情况,所以第一天和当前天要另外计算,中间的可以除以24小时计算,具体如下:
func countDays(t time.Time) int {
tomDay := t.AddDate(0, 0, 1) // 第二天时间
// 计算时间的零点时间
midnight := time.Date(tomDay.Year(), tomDay.Month(), tomDay.Day(), 0, 0, 0, 0, tomDay.Location())
nowTime := time.Now()
if midnight.After(nowTime) {
return 1
}
nowNight := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, t.Location())
hours := nowNight.Sub(midnight).Hours()
return int(hours/24) + 2
}
备注
第二天不能用time.Day()加1计算