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

后端 未结 8 1220
礼貌的吻别
礼貌的吻别 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)
    
    0 讨论(0)
  • 2021-02-01 05:05

    I would do it like this:

    // LastDayOfMonth returns 28-31 - the last day in the month of the time object
    // passed in to the function
    func LastDayOfMonth(t time.Time) int {
        firstDay := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)
        lastDay := firstDay.AddDate(0, 1, 0).Add(-time.Nanosecond)
        return lastDay.Day()
    }
    

    a

    0 讨论(0)
提交回复
热议问题