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


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

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的Unix()函數用於產生本地時間,該時間與UTC中自1970年1月1日起的Unix時間有關。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。

用法:

func Unix(sec int64, nsec int64) Time

在此,“sec”是秒,其類型為int64,而“nsec”是納秒,其類型也是int64。

注意:允許“nsec”超出[0,999999999]範圍是合理的。但是,並非每個“sec”值都具有等效的時間值,並且一個類似的值是1 << 63-1,這是最大的int64值。

返回值:它返回本地時間,該時間等於1970年1月1日在UTC開始的Unix時間。



範例1:

// Golang program to illustrate the usage of 
// time.Unix() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Calling Unix method with 275 seconds 
    // and zero nanoseconds and also 
    // printing output 
    fmt.Println(time.Unix(275, 0).UTC()) 
  
    // Calling Unix method with 0 seconds and 
    // 566 nanoseconds and also printing 
    // output 
    fmt.Println(time.Unix(0, 566).UTC()) 
  
    // Calling Unix method with 456 seconds and 
    // -67 nanoseconds and also printing 
    // output 
    fmt.Println(time.Unix(456, -67).UTC()) 
}

輸出:

1970-01-01 00:04:35 +0000 UTC
1970-01-01 00:00:00.000000566 +0000 UTC
1970-01-01 00:07:35.999999933 +0000 UTC

範例2:

// Golang program to illustrate the usage of 
// time.Unix() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Calling Unix method with 2e1 seconds 
    // and zero nanoseconds and also 
    // printing output 
    fmt.Println(time.Unix(2e1, 0).UTC()) 
  
    // Calling Unix method with 0 seconds and 
    // 1e13 nanoseconds and also printing 
    // output 
    fmt.Println(time.Unix(0, 1e13).UTC()) 
  
    // Calling Unix method with 1e1 seconds and 
    // -1e15 nanoseconds and also printing 
    // output 
    fmt.Println(time.Unix(1e1, -1e15).UTC()) 
}

輸出:

1970-01-01 00:00:20 +0000 UTC
1970-01-01 02:46:40 +0000 UTC
1969-12-20 10:13:30 +0000 UTC

在此,上述代碼中所述的Unix()方法的參數具有包含常數“e”的值,該常數在轉換時會在通常範圍內轉換。




相關用法


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