time.Truncate() Function in Golang With Examples
In Go language, time packages supply functionality for determining as well as viewing time. The Truncate() function in Go language is used to find the outcome of rounding the stated duration ‘d’ towards zero to a multiple of ‘m’ duration. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (d Duration) Truncate(m Duration) Duration
Here, d is the duration of time that will be rounded and m is the multiple.
Return Value: It returns the outcome of rounding the stated duration ‘d’ towards zero to a multiple of ‘m’ duration. But if m is less than or equal to zero then it returns unaltered ‘d’.
Example 1:
// Golang program to illustrate the usage of // Truncate() function // Including main package package main // Importing fmt and time import ( "fmt" "time" ) // Calling main func main() { // Defining duration // of Truncate method tr, _ := time .ParseDuration( "45m32.67s" ) // Prints truncated duration fmt.Printf( "Truncated duration is : %s" , tr.Truncate(2* time .Second)) } |
Output:
Truncated duration is : 45m32s
Here, ‘d’ is rounded to the multiple of m.
Example 2:
// Golang program to illustrate the usage of // Truncate() function // Including main package package main // Importing fmt and time import ( "fmt" "time" ) // Calling main func main() { // Defining duration of Truncate method tr, _ := time .ParseDuration( "7m11.0530776s" ) // Array of m t := [] time .Duration{ time .Microsecond, time .Second, 4 * time .Second, 11 * time .Minute, } // Using for loop and range to // iterate over an array for _, m := range t { // Prints rounded d of all // the items in an array fmt.Printf( "Truncated(%s) is : %s\n" , m, tr.Truncate(m)) } } |
Output:
Truncated(1µs) is : 7m11.053077s Truncated(1s) is : 7m11s Truncated(4s) is : 7m8s Truncated(11m0s) is : 0s
Here, an array of ‘t’ is formed first then a range is used in order to iterate over all the values of duration ‘t’. And at last Truncate() method is used to print all the rounded values of t in the above code.