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


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

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的In()函數用於查找表示相同時刻的聲明的“t”的副本,以及該副本的位置數據(設置為“loc”以供顯示)。如果“loc”為nil,則返回恐慌。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。

用法:

func (t Time) In(loc *Location) Time

在此,“t”是指定時間,“loc”是指定位置,是指向該位置的指針。

返回值:它會返回表示相同時刻的聲明的“t”的副本,並返回該副本的位置數據(已設置為“loc”用於顯示)。如果“loc”為nil,則返回恐慌。

範例1:



// Golang program to illustrate the usage of 
// Time.In() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Defining t for In method 
    t:= time.Date(2019, 12, 13, 3, 23, 43, 02, time.UTC) 
  
    // Defining loc parameter of In method 
    loc:= time.FixedZone("UTC", 6*54*44) 
  
    // Calling In() method 
    res:= t.In(loc) 
  
    // Prints output 
    fmt.Printf("%v\n", res) 
}

輸出:

2019-12-13 07:21:19.000000002 +0357 UTC

範例2:

// Golang program to illustrate the usage of 
// Time.In() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Defining t for In method 
    t:= time.Date(2022, 23, 45, 36, 67, 88, 667, time.UTC) 
  
    // Defining loc parameter of In method 
    loc:= time.FixedZone("UTC-6", -3*66*77) 
  
    // Calling In() method 
    res:= t.In(loc) 
  
    // Prints output 
    fmt.Printf("%v\n", res) 
}

輸出:

2023-12-16 08:54:22.000000667 -0414 UTC-6

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




相關用法


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