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 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts