處理及格式化unix timestamp

unix timestamp 字串形式

若您的timestamp以字串形式存在,請先使用 strconv.ParseInt 把字串轉為 int64格式後再處理,time.Parse並不適用於unix timestamp。

package main
import (
    "fmt"
    "time"
    "strconv"
)
func main() {
    i, err := strconv.ParseInt("1518328047", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)       // 輸出:2018-02-11 05:47:27 +0000 UTC
}

若timestamp為數字(int)型態

package main
import (
    "fmt"
    "time"
)
func main() {
   tm := time.Unix(1518328047, 0)
   fmt.Println(tm)   // 2018-02-11 05:47:27 +0000 UTC
}

把unix timestamp轉為 RFC3390

package main
import (
 "fmt"
 "time"
)
func main() {

 unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 

 unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

 fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
 fmt.Println("unix time stamp in unitTimeInRFC3339 format :---->",unitTimeInRFC3339)
}

// 輸出
unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z