2021-02-28 23:59:592021-03-01 00:00:00
(T2.Unix()-T1.Unix()) / 86400

因此针对上述这种需求自己实现了一个函数用于获取两个时间的自然天之差,具体如下:

基本思路

diffSec/86400tmpDayst11t11t2t11t2tmpDaystmpDays+1

代码实现

func diffNatureDays(t1, t2 int64) int {
    if t1 == t2 {
        return -1
    }
    if t1 > t2 {
        t1, t2 = t2, t1
    }

    diffDays := 0
    secDiff := t2 - t1
    if secDiff > SecondsOfDay {
        tmpDays := int(secDiff / SecondsOfDay)
        t1 += int64(tmpDays) * SecondsOfDay
        diffDays += tmpDays
    }

    st := time.Unix(t1, 0)
    et := time.Unix(t2, 0)
    dateFormatTpl := "20060102"
    if st.Format(dateFormatTpl) != et.Format(dateFormatTpl) {
        diffDays += 1
    }

    return diffDays
}