Skip to content

Instantly share code, notes, and snippets.

@edr3x
Created April 19, 2024 08:19
Show Gist options
  • Save edr3x/5d836a5fdd76adbcba0fad0130ed984d to your computer and use it in GitHub Desktop.
Save edr3x/5d836a5fdd76adbcba0fad0130ed984d to your computer and use it in GitHub Desktop.
Extract timestamp from UUIDv7 string

Code

func extractTimestamp(uuid string) (time.Time, error) {
	parts := strings.Split(uuid, "-")
	millisecondsStr := parts[0] + parts[1]
	milliseconds, err := strconv.ParseInt(millisecondsStr, 16, 64)
	if err != nil {
		return time.Time{}, err
	}
	timestampSeconds := milliseconds / 1000
	return time.Unix(timestampSeconds, 0), nil
}

Example

package main

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/google/uuid"
)

// Extracts timestamp from generated UUIDv7
func extractTimestamp(uuid string) (time.Time, error) {
	parts := strings.Split(uuid, "-")
	millisecondsStr := parts[0] + parts[1]
	milliseconds, err := strconv.ParseInt(millisecondsStr, 16, 64)
	if err != nil {
		return time.Time{}, err
	}
	timestampSeconds := milliseconds / 1000
	return time.Unix(timestampSeconds, 0), nil
}

func main() {
	// Generate a UUIDv7
	uuid, err := uuid.NewV7()
	if err != nil {
		fmt.Println("Error generating uuidv7:", err)
		return
	}

	timestamp, err := extractTimestamp(uuid.String())
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Current Time: ", timestamp)
	fmt.Println("UTC Time:", timestamp.UTC())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment