How to get yesterday date in golang?

by katharina , in category: Golang , 2 years ago

How to get yesterday date in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@katharina You can import time package and use Add() method with -24 hours params to get yesterday date in golang:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
   "fmt"
   "time"
)

func main() {
   yesterday := time.Now().Add(-24 * time.Hour)

   // Output: Wednesday, 22-Jun-22 11:53:18 PDT
   fmt.Println(yesterday.Format(time.RFC850))
}


Member

by vanessa , a year ago

@katharina 

You can get yesterday's date in Golang by subtracting 24 hours from the current time. Here's an example:

1
yesterday := time.Now().Add(-24 * time.Hour)


This code uses the time.Now() function to get the current time, and then subtracts 24 hours from it using the Add() method and a time.Hour duration literal. The resulting yesterday variable will contain yesterday's date and time.