Golang time.Truncate()函数及示例

Golang time.Truncate()函数及示例

在Go语言中,time包提供了用于确定和查看时间的功能。在Go语言中, Truncate()函数 用于找到将指定的持续时间’d’向零舍入到多个’m’持续时间的结果。此外,此函数在时间包中定义。在此处,您需要导入“时间”包以使用这些功能。

语法:

func (d Duration) Truncate(m Duration) Duration

在此处,’d’是要舍入的时间持续时间,’m’是多个持续时间。

返回值:它返回将指定的持续时间“d”向零舍入到多个持续时间“m”的结果。但是,如果’m’小于或等于零,则返回未更改的’d’。

示例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))
} 

输出:

Truncated duration is : 45m32s

在此处,’d’舍入为’m’的倍数。

示例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))
    }
} 

输出:

Truncated(1µs) is : 7m11.053077s
Truncated(1s) is : 7m11s
Truncated(4s) is : 7m8s
Truncated(11m0s) is : 0s

在此处,首先形成一个’t’的数组,然后使用范围以便遍历所有’d’的值。最后,在上述代码中使用Truncate()方法打印所有’t’的舍入值。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程