How to subtract two times in Go

Overview

While working with date-time in your application, the need to subtract one time from the other will eventually be part of the application’s features.

We will learn to subtract two times using the Sub() method in this shot.

Syntax

time1.Sub(time2)

Parameter

The Sub() method accepts the shorter time parameter and is attached to the larger time.

Example

package main
import "fmt"
import "time"
func main() {
time := time.Now()
time1:=time.AddDate(0,0,1)
time2:=time.AddDate(0,0,2)
diff := time2.Sub(time1)
fmt.Println("Current date and time is: ", diff.String())
}

Explanation

We subtract tomorrow from next tomorrow in the example above.

  1. Line 7: We use Now() to get the current time.

  2. Lines 8-9: We use AddDate() to add the dates. We add one day to time1 and two days to time2.

  3. Line 10: We use Sub() to subtract two times. Here, we subtract time1 from time2

  4. Line 11: We use String() to convert the output to a string data type.

Free Resources