在 Go 语言中,时间包提供了确定和查看时间的功能。 Go 语言中的Time.Sub()函数用于产生执行操作 tu 所获得的持续时间。如果此处的输出超过 Duration “d” 中可以存储的最大值或最小值,则将返回最大值或最小值。而且,这个函数是在time包下定义的。在这里,您需要导入“time”包才能使用这些功能。
Syntax:
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.
示例 1:
func (t Time) Sub(u Time) Duration
输出:
// 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)
}
示例 2:
t-d = 10462h45m16.000000036s
输出:
// 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)
}
这里,上面代码中的时间“t”和“u”的值超出了通常的范围,但它们在转换时被归一化。