Golang中长整型时间戳转换问题探讨

Golang中长整型时间戳转换问题探讨 你好

我正在使用Go语言的http.Client处理一个REST API。其中一个响应是UNIX时间戳。 输入是13位数字,我无法使用time.Unix将其转换为时间,因为它只接受10位数字。

我通过以下方式解决了这个问题: https://play.golang.org/p/foCLoASas18

  1. 将输入转换为字符串。
  2. 只取前10个字符。
  3. 将其转换回整数。
  4. 转换为UNIX时间。

有更好的解决方法吗?

2 回复

你好

我想我找到了一个更简单的解决方案:

https://play.golang.org/p/kLRPVS85wa4

将输入除以1000,将其转换为int64,然后从Unix时间转换为time.Time。

func main() {
    fmt.Println("hello world")
}

更多关于Golang中长整型时间戳转换问题探讨的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go中处理13位毫秒级时间戳时,更优雅的方式是直接使用time.UnixMilli()函数(Go 1.17+)。以下是两种推荐方案:

方案一:使用time.UnixMilli()(推荐)

package main

import (
    "fmt"
    "time"
)

func main() {
    // 13位毫秒时间戳
    timestamp := int64(1672531199000)
    
    // 直接转换为time.Time
    t := time.UnixMilli(timestamp)
    fmt.Println(t) // 2022-12-31 23:59:59 +0000 UTC
}

方案二:手动计算(兼容旧版本)

package main

import (
    "fmt"
    "time"
)

func main() {
    timestamp := int64(1672531199000)
    
    // 分别获取秒和纳秒部分
    sec := timestamp / 1000
    nsec := (timestamp % 1000) * 1e6
    
    t := time.Unix(sec, nsec)
    fmt.Println(t) // 2022-12-31 23:59:59 +0000 UTC
}

实际API响应处理示例:

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type APIResponse struct {
    Timestamp int64 `json:"timestamp"`
    Data      string `json:"data"`
}

func main() {
    jsonData := `{"timestamp": 1672531199000, "data": "example"}`
    
    var resp APIResponse
    json.Unmarshal([]byte(jsonData), &resp)
    
    // 转换时间戳
    t := time.UnixMilli(resp.Timestamp)
    fmt.Printf("Time: %v, Data: %s\n", t, resp.Data)
}

这两种方案都避免了字符串转换的开销,直接进行数值计算,性能更好且代码更简洁。

回到顶部