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 mainimport "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.
-
Line 7: We use
Now()to get the current time. -
Lines 8-9: We use
AddDate()to add the dates. We add one day totime1and two days totime2. -
Line 10: We use
Sub()to subtract two times. Here, we subtracttime1fromtime2 -
Line 11: We use
String()to convert the output to a string data type.