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


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

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的Date()函數用於在指定位置的正確時區中找到與yyyy-mm-dd hh:mm:ss + nsec納秒等效的日期時間。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。

用法:

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

在此,“loc”指向該位置。

返回值:它會在轉換的兩個關聯區域之一中返回適當的時間,但不能保證會返回哪個時間。如果給定的“loc”為nil,它將返回恐慌。

注意:此處,月,日,小時,分鍾,秒和秒的值可以大於正常範圍,但在轉換過程中會自動將其標準化。例如,如果日期為4月34日,則將其轉換為5月1日。



範例1:

// Golang program to illustrate the usage of 
// time.Date() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Calling Date() method  
    // with all its parameters 
    tm := time.Date(2020, time.April, 
        11, 21, 34, 01, 0, time.UTC) 
  
    // Using Local() for location and printing 
    // the stated time and date in UTC 
    fmt.Printf("%s", tm.Local()) 
}

輸出:

2020-04-11 21:34:01 +0000 UTC

範例2:

// Golang program to illustrate the usage of 
// time.Date() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Calling Date() method  
    // with all its parameters 
    tm := time.Date(2020, time.April,  
          34, 25, 72, 01, 0, time.UTC) 
  
    // Using Local() for location and printing 
    // the stated time and date in UTC 
    fmt.Printf("%s", tm.Local()) 
}

輸出:

2020-05-05 02:12:01 +0000 UTC

在這裏,天,小時和分鍾的值的範圍超出了正常範圍,但在轉換過程中已將它們標準化。




相關用法


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