How to Subtract time.Duration from time in Go

To subtract time.Duration from time.Time value in Golang, you can use the Add() method with a negative duration. The AddDate() function is not suitable for subtracting a time.Duration from a time.Time value because it works with years, months, and days, not durations like hours, minutes, or seconds.

package main

import (
  "fmt"
  "time"
)

func main() {
  now := time.Now()
  fmt.Printf("Current time: %v\n", now)

  duration := 2 * time.Hour
  pastTime := now.Add(-duration)
  fmt.Printf("Time %v ago: %v\n", duration, pastTime)
}

Output

Current time: 2023-03-25 17:31:48.241949 +0530 IST m=+0.000212876
Time 2h0m0s ago: 2023-03-25 15:31:48.241949 +0530 IST m=-7199.999787124

In this code example, we get the current time using time.Now() and store it in the now variable.

In the next step, we created a time.Duration value called duration represents 2 hours.

To subtract the duration from the current time, we call the Add method on now with a negative value of duration (-duration). The result is stored in the pastTime variable.

That’s it.

Leave a Comment