如何提取unix时间戳并获取日期

aaj*_*aaj 3 go

我有一个整数

x := 1468540800
Run Code Online (Sandbox Code Playgroud)

我想从 Golang 中的 unix 时间戳中获取日期。我已经尝试过time.ParseDuration,但看起来这不是从中提取日期的正确方法。转换应该像这样发生http://www.unixtimestamp.com/index.php
我打算转换成 ISO 8601 格式可能是。我想要像2016-09-14.

小智 5

您可以t := time.Unix(int64(x), 0)将位置设置为当地时间来使用。
或者t := time.Unix(int64(x), 0).UTC()将位置设置为 UTC 来使用。

您可以使用t.Format("2006-01-02")格式化代码(在Go Playground上尝试):

package main

import (
    "fmt"
    "time"
)

func main() {
    x := 1468540800
    t := time.Unix(int64(x), 0).UTC() //UTC returns t with the location set to UTC.
    fmt.Println(t.Format("2006-01-02"))
}
Run Code Online (Sandbox Code Playgroud)

输出:

2016-07-15
Run Code Online (Sandbox Code Playgroud)