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

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


Not sure when AddDate(...) was added to time.Time, but quite possibly it was added after this question had its prime time :)

Here's another way to achieving the same with time.Time.AddDate(...) -

func BeginningOfMonth(date time.Time)  (time.Time) {
    return date.AddDate(0, 0, -date.Day() + 1)
}

func EndOfMonth(date time.Time) (time.Time) {
    return date.AddDate(0, 1, -date.Day())
}

Then you could use today := time.Now() and pass it over to one/both of the functions like so - eom := EndOfMonth(today) to get the appropriate date.

If time, DST and such are important, it should be pretty straightforward to ornament those details on top of it once you get the date.

Finally, here's a playground link where you can play around with it - https://play.golang.org/p/DxnGuqh6g4k

Tags:

Time

Date

Go