可以使用 time.Parse 函数将时间字符串转换为 time.Time 类型,然后使用 time.Time.UnixNano() 方法将其转换为纳秒级别的时间戳,最后将其除以 1e6 转换为毫秒级别的时间戳。

示例代码:

package main

import (
    "fmt"
    "time"
)

func main() {
    timeStr := '2021-01-01 00:00:00'
    layout := '2006-01-02 15:04:05'
    t, err := time.Parse(layout, timeStr)
    if err != nil {
        fmt.Println('parse time error:', err)
        return
    }
    timestamp := t.UnixNano() / 1e6 // 转换为毫秒级别的时间戳
    fmt.Println(timestamp)
}

输出结果:

1609459200000
Golang 时间字符串转毫秒时间戳

原文地址: https://www.cveoy.top/t/topic/f046 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录