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

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

    This can also be a solution:

    currentTimestamp := time.Now().UTC()
    currentYear, currentMonth, _ := currentTimestamp.Date()
    currentLocation := currentTimestamp.Location()
    
    firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, currentLocation)
    lastOfMonth := time.Date(currentYear, currentMonth+1, 0, 23, 59, 59, 999999999, currentLocation)
    
    fmt.Println(firstOfMonth)
    fmt.Println(lastOfMonth)
    

    Output:

    firstOfMonth: 2019-11-01 00:00:00 +0000 UTC
    lastOfMonth: 2019-11-30 23:59:59.999999999 +0000 UTC
    

    Click here to try it out: Playground Link

提交回复
热议问题