Get the first and last day of current month

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

Leave a Comment