How to get yesterday date in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To get yesterday’s date, golang provides the AddDate() method just pass -1 as a parameter it will return yesterday’s date for example.

time.Now().AddDate(0, 0, -1)

The AddDate() returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

Let’s start today’s tutorial How to get yesterday’s date in golang?

Here, we will use time.Now() method to get current date, after that we will use AddDate(0, 0, -1) method to minus 1 day from current date.

let’s write a code.

package main

import "fmt"
import "time"

func main() {
	today := time.Now()
	yesterday := today.AddDate(0, 0, -1)

	fmt.Printf("Today    : %02d-%02d-%04d\n", today.Day(), today.Month(), today.Year())
	fmt.Printf("Yesterday : %02d-%02d-%04d", yesterday.Day(), yesterday.Month(), yesterday.Year())
}

In the above example, we have print both date current date and yesterdate. let’s check the output.

check, get yesterday date, golang

Try it yourself

All the best 👍

Follow me on Twitter