Search code examples
dategotime

Get the first and last day of current month


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 get the last day of this month. Something like this:

package main

import (
    "fmt"
    "time"
)

func main() {

    date := time.Now()
    nextMonth := date.Add(time.Month)
    LastDay := nextMonth.Add(-time.Hour * 24)

    fmt.Println(LastDay)

}

Solution

  • You can use now library, it really simple :

    now.BeginningOfMonth()    // 2013-11-01 00:00:00 Fri
    now.EndOfMonth()          // 2013-11-30 23:59:59.999999999 Sat
    

    Please take a look here for detail : https://github.com/jinzhu/now