當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang time.Time.Round()用法及代碼示例

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的Time.Round()函數用於查找將指定時間“t”舍入為從零時間開始的給定持續時間“d”的最接近倍數的輸出。 mid-values的舍入行為是舍入的。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。

用法:

func (t Time) Round(d Duration) Time

在此,“t”是指定的時間,而“d”是給定的持續時間。

注意:Round()方法以從零時間開始的絕對持續時間的形式處理時間。但是,它不適用於當時的布局形式。

返回值:它返回將給定時間“t”舍入為指定持續時間“d”的最接近倍數的輸出。其中,如果d小於或等於零,那麽它將從任何單調時鍾讀數中返回“t”,但不會改變。



範例1:

// Golang program to illustrate the usage of 
// Time.Round() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Defining t for Round method 
    t:= time.Date(2013, 7, 6, 11, 34, 13, 60, time.UTC) 
  
    // Defining duration 
    d:= (60 * time.Second) 
  
    // Calling Round() method 
    res:= t.Round(d) 
  
    // Prints output 
    fmt.Printf("The time after rounding is:%v\n", res) 
}

輸出:

The time after rounding is:2013-07-06 11:34:00 +0000 UTC

範例2:

// Golang program to illustrate the usage of 
// Time.Round() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Defining t for Round method 
    t:= time.Date(2033, 76, 96, 100, 89, 99, 6665, time.UTC) 
  
    // Defining duration 
    d:= (4 * time.Minute) 
  
    // Calling Round() method 
    res:= t.Round(d) 
  
    // Prints output 
    fmt.Printf("The time after rounding is:%v\n", res) 
}

輸出:

The time after rounding is:2039-07-09 05:32:00 +0000 UTC

此處,以上代碼中說明的“t”的值不在通常範圍內,但在轉換時已標準化。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 time.Time.Round() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。