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

huangapple go评论166阅读模式
英文:

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

问题

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

例如:

var milleSecond int64
milleSecond = 1645286399999 //我的本地时间:2022年2月19日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

英文:

How do i convert millisecond (uint64) into Time Format RFC3999 with millisecond (string) in GO?

For example:

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) 

Actual Result: 2022-02-19T11:59:59-04:00

Expected Result(should be): 2022-02-19T11:59:59.999-04:00

答案1

得分: 2

您正在要求一个以RFC3339格式化的字符串,其中秒数精确到最近的毫秒。时间包中没有针对此格式的字符串(只有整秒和纳秒精度),但您可以自己制作。

以下是以最近的纳秒为单位的字符串,从标准库中复制:

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

您可以通过删除.999999999(将时间精确到最近的纳秒,删除尾随的零)并将其更改为.000(将时间精确到最近的毫秒,不删除尾随的零)来轻松制作毫秒版本。此格式在包文档的time.Layout下有文档记录:https://pkg.go.dev/time#pkg-constants

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

代码(playground链接):

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
英文:

You are asking for an RFC3339 formatted string, with seconds reported to the nearest millisecond. There's no format string in the time package for this (only with whole seconds and nanosecond accuracy), but you can make your own.

Here's the string for seconds to the nearest nanosecond, copied from the standard library:

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

You can make a millisecond version of this easily enough by removing the .999999999 (report time to the nearest nanosecond, removing trailing zeros) to .000 (report time to the nearest millisecond, don't remove trailing zeros). This format is documented under time.Layout in the package docs https://pkg.go.dev/time#pkg-constants:

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

Code (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))
}

Output:

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

huangapple
  • 本文由 发表于 2022年2月19日 16:15:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/71183272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定