time.Since() with months and years

前端 未结 5 1667
悲哀的现实
悲哀的现实 2020-12-01 11:20

I am trying to convert a timestamp like this:

2015-06-27T09:34:22+00:00

to a time since format so it would say like 9 months ago 1 day 2 ho

5条回答
  •  隐瞒了意图╮
    2020-12-01 11:48

    Something like this would work, probably not the most efficient but it is as accurate as you gonna get:

    func main() {
        a := time.Date(2015, 10, 15, 0, 0, 0, 0, time.UTC)
        b := time.Date(2016, 11, 15, 0, 0, 0, 0, time.UTC)
        fmt.Println(monthYearDiff(a, b))
    }
    
    func monthYearDiff(a, b time.Time) (years, months int) {
        m := a.Month()
        for a.Before(b) {
            a = a.Add(time.Hour * 24)
            m2 := a.Month()
            if m2 != m {
                months++
            }
            m = m2
        }
        years = months / 12
        months = months % 12
        return
    }
    

    playground

提交回复
热议问题