How to Subtracting time.Duration from Time in Go

Created
Modified

Using time.Duration Function

A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years. For example,

package main

import (
  "fmt"
  "time"
)

func main() {
  now := time.Now()

  m := 10
  t := now.Add(time.Duration(m) * time.Minute)
  fmt.Println(now.Format(time.ANSIC))
  fmt.Println(t.Format(time.ANSIC))

  t = now.Add(-10 * time.Second)
  fmt.Println(t.Format(time.ANSIC))
}
Tue May  3 11:00:55 2022
Tue May  3 11:10:55 2022
Tue May  3 11:00:45 2022

Using time.ParseDuration Function

ParseDuration parses a duration string. When you need to substract an hour and a half, you can do that like so:

package main

import (
  "fmt"
  "time"
)

func main() {
  now := time.Now()

  duration, _ := time.ParseDuration("-1.5h")
  t := now.Add(duration)
  fmt.Println(now.Format(time.ANSIC))
  fmt.Println(t.Format(time.ANSIC))

  // hours, _ := time.ParseDuration("10h")
  // complex, _ := time.ParseDuration("1h10m10s")
  // micro, _ := time.ParseDuration("1µs")
  // The package also accepts the incorrect but common prefix u for micro.
  // micro2, _ := time.ParseDuration("1us")
}
Tue May  3 11:04:54 2022
Tue May  3 09:34:54 2022

Related Tags