golang中计算两个日期相差的月和年
time包有个函数Parse可以将时间字符串解析成Time对象,而Time对象有个Sub方法可以计算与某个时间的差,返回值是Duration对象,而Duration有一个Seconds方法,除以86400就是天数,再除以365就是多少年了
- 计算日期相差多少个月
func MonthBetweenTwoDates(start, end string) int {
startTime,_ := time.Parse("2006-01-02", start)
endTime,_ := time.Parse("2006-01-02", start)
months := 0
month := startTime.Month()
for startTime.Before(endTime) {
startTime = startTime.Add(time.Hour * 24)
nextMonth := startTime.Month()
if nextMonth != month {
months++
}
month = nextMonth
}
return months
}
fmt.Println(MonthBetweenTwoDates("2019-01-01", "2021-8-01"))
2.计算日期相差多少年
func YearBetweenTwoDates(start, end string) int {
startTime,_ := time.Parse("2006-01-02", start)
endTime,_ := time.Parse("2006-01-02", start)
diff := endTime.Sub(startTime)
return int(diff.Seconds() / 86400 / 365)
}
fmt.Println(YearBetweenTwoDates("2019-01-01", "2021-8-01"))