Search code examples
gouuid

How to convert UUID timestamp to ISO date Golang


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?


Solution

  • 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