Related Articles
time.Time.Sub() Function in Golang With Examples
• Last Updated : 19 Apr, 2020

In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Sub() function in Go language is used to yield the duration obtained by performing the operation t-u. And if the output here surpasses the maximum or the minimum value that can be stored in a Duration “d” then the maximum or the minimum duration will be returned. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.

Syntax:

```func (t Time) Sub(u Time) Duration
```

Here, “t” and “u” are the stated time.

Note: In order to calculate “t-d” for a given duration “d” you need to use t.Add(-d).

Return value: It returns the duration obtained by performing the operation t-u.

Example 1:

 `// Golang program to illustrate the usage of ` `// Time.Sub() function ` ` `  `// Including main package ` `package main ` ` `  `// Importing fmt and time ` `import ( ` `    ``"fmt"` `    ``"time"` `) ` ` `  `// Calling main ` `func main() { ` ` `  `    ``// Defining t and u for Sub method ` `    ``t := ``time``.Date(2020, 11, 14, 16, ` `               ``45, 16, 36, ``time``.UTC) ` `    ``u := ``time``.Date(2019, 9, 5, 18, 0, ` `                      ``0, 0, ``time``.UTC) ` ` `  `    ``// Calling Sub method ` `    ``subtract := t.Sub(u) ` ` `  `    ``// Prints output ` `    ``fmt.Printf(``"t-d = %v\n"``, subtract) ` `} `

Output:

```t-d = 10462h45m16.000000036s
```

Example 2:

 `// Golang program to illustrate the usage of ` `// Time.Sub() function ` ` `  `// Including main package ` `package main ` ` `  `// Importing fmt and time ` `import ( ` `    ``"fmt"` `    ``"time"` `) ` ` `  `// Calling main ` `func main() { ` ` `  `    ``// Defining t and u for Sub method ` `    ``t := ``time``.Date(2020, 11, 14, 34,  ` `               ``67, 98, 63, ``time``.UTC) ` `    ``u := ``time``.Date(2019, 9, 5, 28,  ` `            ``66, 89, 100, ``time``.UTC) ` ` `  `    ``// Calling Sub method ` `    ``subtract := t.Sub(u) ` ` `  `    ``// Prints output ` `    ``fmt.Printf(``"t-d = %v\n"``, subtract) ` `} `

Output:

```t-d = 10470h1m8.999999963s
```

Here, the times “t” and “u” stated in the above code have values that are out of usual range but they are normalized while conversion.

My Personal Notes arrow_drop_up
Recommended Articles
Page :