How to get the first and last day of the current month in Go

Created
Modified

Using time.AddDate Function

AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example,

package main

import (
  "fmt"
  "time"
)

func main() {

  t := time.Now()
  // format := "2006-01-02 15:04:05"
  // t, _ = time.Parse(format, "2022-02-05 12:00:00")

  // the first day
  firstOfMonth := t.AddDate(0, 0, -t.Day()+1)
  s := firstOfMonth.Format(time.RFC3339)
  fmt.Println(s)

  // the last day
  lastOfMonth := t.AddDate(0, 1, -t.Day())
  s = lastOfMonth.Format(time.RFC3339)
  fmt.Println(s)
}
2022-04-01T09:19:25+09:00
2022-04-30T09:19:25+09:00

By far, this is the most elegant approach. 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.

Using time.Date Function

You can use time.Date function, it really simple. For example,

package main

import (
  "fmt"
  "time"
)

func main() {

  t := time.Now()

  y, m, _ := t.Date()
  loc := t.Location()
  // the first day
  firstOfMonth := time.Date(y, m, 1, 0, 0, 0, 0, loc)
  s := firstOfMonth.Format(time.RFC3339)
  fmt.Println(s)

  // the last day
  lastOfMonth := time.Date(y, m+1, 1, 0, 0, 0, -1, loc)
  s = lastOfMonth.Format(time.RFC3339)
  fmt.Println(s)
}
2022-04-01T00:00:00+08:00
2022-04-30T23:59:59+08:00

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

Related Tags