Get the first and last day of current month in Go/Golang?

后端 未结 8 1221
礼貌的吻别
礼貌的吻别 2021-02-01 04:07

I\'m trying to get the first and last day of the current month. You can add days and hours but not the month, which I was thinking of subtracting one day from the next month to

8条回答
  •  执笔经年
    2021-02-01 04:45

    Not sure when AddDate(...) was added to time.Time, but quite possibly it was added after this question had its prime time :)

    Here's another way to achieving the same with time.Time.AddDate(...) -

    func BeginningOfMonth(date time.Time)  (time.Time) {
        return date.AddDate(0, 0, -date.Day() + 1)
    }
    
    func EndOfMonth(date time.Time) (time.Time) {
        return date.AddDate(0, 1, -date.Day())
    }
    

    Then you could use today := time.Now() and pass it over to one/both of the functions like so - eom := EndOfMonth(today) to get the appropriate date.

    If time, DST and such are important, it should be pretty straightforward to ornament those details on top of it once you get the date.

    Finally, here's a playground link where you can play around with it - https://play.golang.org/p/DxnGuqh6g4k

提交回复
热议问题