如何在 GO 中将毫秒 (uint64) 转换为带毫秒(字符串)的时间格式 RFC3999

How to convert millisecond (uint64) into Time Format RFC3999 with millisecond (string) in GO

如何在 GO 中将毫秒 (uint64) 转换为带毫秒(字符串)的时间格式 RFC3999?

例如:

var milleSecond int64
milleSecond = 1645286399999 //My Local Time : Sat Feb 19 2022 23:59:59

var loc = time.FixedZone("UTC-4", -4*3600)

string1 := time.UnixMilli(end).In(loc).Format(time.RFC3339) 

实际结果:2022-02-19T11:59:59-04:00

预期结果(应该是):2022-02-19T11:59:59.999-04:00

您正在请求一个 RFC3339 格式的字符串,秒数报告为最接近的毫秒数。时间包中没有格式字符串(只有整秒和纳秒精度),但你可以自己制作。

这是从标准库复制来的精确到纳秒的秒字符串:

RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"

您可以通过删除 .999999999(报告时间到最近的纳秒,删除尾随零)到 .000(报告时间到最近的毫秒,不要'删除尾随零)。此格式记录在包文档 time.Layouthttps://pkg.go.dev/time#pkg-constants:

RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"

代码(playground link):

package main

import (
    "fmt"
    "time"
)

const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"

func main() {
    ms := int64(1645286399999) //My Local Time : Sat Feb 19 2022 23:59:59
    var loc = time.FixedZone("UTC-4", -4*3600)
    fmt.Println(time.UnixMilli(ms).In(loc).Format(RFC3339Milli))
}

输出:

2022-02-19T11:59:59.999-04:00