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

后端 未结 8 1352
礼貌的吻别
礼貌的吻别 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 05:05

    The @Apin's answer is dangerous because the now lib makes many wrong assumptions (it bit me in the foot too).
    The now lib doesn't consider daylight saving times and many other things: https://github.com/jinzhu/now/issues/13

    This is how I'm doing it:

    t := time.Now()
    firstday := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.Local)
    lastday := firstday.AddDate(0, 1, 0).Add(time.Nanosecond * -1)
    

提交回复
热议问题