Home > OS >  How to find previous month and year in golang
How to find previous month and year in golang

Time:12-02

I just found AddDate() does not always works as expected.

ex:

mayEndDate := time.Date(2021, 5, 31, 12, 00, 00, 00, time.UTC)
finalDate := endOfMay.AddDate(0, -1, 0)

here output:

  • myEndDate = 2021-05-31 12:00:00 0000 UTC
  • finalDate = 2021-05-01 12:00:00 0000 UTC

I was expecting finalDate to be in April. After reading the documentation, I found out the reason.

AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.

My question: how to now correctly find out the last month's date from today's date?

CodePudding user response:

Get the current month using Month(), then from there it’s pretty simple to get the previous one:

currentMonth := mayEndDate.Month()
previousMonth := currentMonth - 1
if currentMonth == time.January {
    previousMonth = time.December
}

CodePudding user response:

I just want to know what was the previous month. ex. if date= 1st march 2022, then prev month & year:- feb 2022, if date = 1st dec 2021, then prev month & year: dec 2020, if date=28 feb 2022, then prev month & year: jan 2022,


package main

import (
    "fmt"
    "time"
)

func prevMonth(t time.Time) (int, time.Month) {
    y, m, _ := t.Date()
    y, m, _ = time.Date(y, m-1, 1, 0, 0, 0, 0, time.UTC).Date()
    return y, m
}

func main() {
    endOfMay := time.Date(2021, 5, 31, 12, 00, 00, 00, time.UTC)
    fmt.Println(endOfMay)
    fmt.Println(prevMonth(endOfMay))
}

https://go.dev/play/p/rP25ramRrZ3

2021-05-31 12:00:00  0000 UTC
2021 April
  •  Tags:  
  • go
  • Related