如何将UUID时间戳转换为ISO日期格式(Golang)

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

How to convert UUID timestamp to ISO date Golang

问题

我正在尝试使用Google的库来为事件生成UUID。现在我需要按照它们的创建时间对事件进行筛选。

import (
	"fmt"

	"github.com/google/uuid"
)

func main() {
	id := uuid.New()
	fmt.Println(id.Time())
}

输出:

1118302296282601152

接下来我可以尝试什么?

英文:

I'm trying to use Google's library to generate a UUID for an event.
And now I need to filter the events by their time of creation.

import (
	"fmt"

	"github.com/google/uuid"
)

func main() {
	id := uuid.New()
	fmt.Println(id.Time())
}

Output:

1118302296282601152

What can I try next?

答案1

得分: 2

New 创建一个新的随机 UUID 或者发生 panic。New 等同于以下表达式:

NewUUID 基于当前的 NodeID、时钟序列和当前时间生成一个版本 1 的 UUID。如果 NodeID 没有通过 SetNodeID 或 SetNodeInterface 设置,则会自动设置。如果无法设置 NodeID,则 NewUUID 返回 nil。如果时钟序列没有通过 SetClockSequence 设置,则会自动设置。如果 GetTime 无法返回当前时间,则 NewUUID 返回 nil 和一个错误。

因此,使用 uuid.NewUUID() 替代 New,这将给你正确的结果。

id, _ := uuid.NewUUID()
t := id.Time()
sec, nsec := t.UnixTime()
timeStamp := time.Unix(sec, nsec)

fmt.Printf("你的唯一标识是:%s \n", id)
fmt.Printf("该标识生成于:%v \n", timeStamp)

输出:

你的唯一标识是:5bdf0fe4-0cc4-11ed-8978-025041000001 
该标识生成于:2022-07-26 14:51:41.2821988 +0530 IST
英文:

New creates a new random UUID or panics. New is equivalent to the expression

NewUUID returns a Version 1 UUID based on the current NodeID and clock sequence, and the current time. If the NodeID has not been set by SetNodeID or SetNodeInterface then it will be set automatically. If the NodeID cannot be set NewUUID returns nil. If clock sequence has not been set by SetClockSequence then it will be set automatically. If GetTime fails to return the current NewUUID returns nil and an error.

So use the uuid.NewUUID() instead of New. This will give you the correct result.

id, _ := uuid.NewUUID()
t := id.Time()
sec, nsec := t.UnixTime()
timeStamp := time.Unix(sec, nsec)

fmt.Printf("Your unique id is: %s \n", id)
fmt.Printf("The id was generated at: %v \n", timeStamp)

Output:

    Your unique id is: 5bdf0fe4-0cc4-11ed-8978-025041000001 
    The id was generated at: 2022-07-26 14:51:41.2821988 +0530 IST

huangapple
  • 本文由 发表于 2022年7月26日 17:16:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/73120750.html
匿名

发表评论

匿名网友

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

确定