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.
time1.Sub(time2)
The Sub()
method accepts the shorter time parameter and is attached to the larger time.
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())}
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 to time1
and two days to time2
.
Line 10: We use Sub()
to subtract two times. Here, we subtract time1
from time2
Line 11: We use String()
to convert the output to a string data type.