Subtracting time.Duration from time.Time in Go: how to do it correctly?
Hello, colleagues! I just started learning Go and encountered a problem when working with dates and time. I need to subtract, for example, 24 hours from the current moment to get the time "yesterday at the same time". I'm writing something like:
```go
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
yesterday := now - 24 * time.Hour // Error!
fmt.Println(yesterday)
}
```
But the compiler gives an error: `invalid operation: operator - not defined on time.Time`. I understand that `time.Time` is a structure, not a number, and you cannot directly subtract from it. I tried using `time.Duration`, but got confused. The documentation says that `time.Time` can be added to `time.Duration`, but how do you subtract correctly? I need to get an exact value to later compare with another...
No answers yet.
Log in to leave an answer
Blogs