time.Time.Sub() Function in Golang With Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

t-d = 10462h45m16.000000036s

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.