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

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

    time.Month is a type, not a value, so you can't Add it. Also, your logic is wrong because if you add a month and subtract a day, you aren't getting the end of the month, you're getting something in the middle of next month. If today is 24 April, you'll get 23 May.

    The following code will do what you're looking for:

    package main
    
    import (
        "time"
        "fmt"
    )
    
    func main() {
        now := time.Now()
        currentYear, currentMonth, _ := now.Date()
        currentLocation := now.Location()
    
        firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, currentLocation)
        lastOfMonth := firstOfMonth.AddDate(0, 1, -1)
    
        fmt.Println(firstOfMonth)
        fmt.Println(lastOfMonth)
    }
    

    Playground link

提交回复
热议问题