bwmarrin / snowflake

A simple to use Go (golang) package to generate or parse Twitter snowflake IDs
BSD 2-Clause "Simplified" License
2.98k stars 371 forks source link

Request: A function to get ID at perticular instance of time in past #24

Open msonawane opened 4 years ago

msonawane commented 4 years ago

Usecase: snowflake as database primary key. it will be useful to get all records inserted before 1 month.
It will be great to have a function that: 1) given a time in past generates ID 2) ignores node id ?

bwmarrin commented 4 years ago

I'm sorry for not noticing this issue sooner - but here I am :)

I'm a bit confused on your use case, maybe you can give me a bit more context?

Are you wanting to generate these just for the purpose of doing a sql query? So you can query a database for all records where the IDs created with in a given time frame?

msonawane commented 4 years ago

yes

bwmarrin commented 4 years ago

Hmn, I suppose this is a bit tricky. I'm not entirely sure if this should be in the library - but I'm not opposed to it if I can come up with a good method name for it :)

Here's a example of how to accomplish this

// Generate a Go Datetime, you could use time.X funcs to get a value at a specific date/time
dt := time.Now()

// Convert it into Unix timestamp in milliseconds and offset it by the snowflake Epoch
t = (dt.UnixNano() / 1000000) - (snowflake.Epoch)

// shift it over 22 bits, this should be (nodebits + stepbits)
t = (t) << 22

// Print the result
fmt.Printf("Int64   t: %d\n", t)
codemedic commented 3 years ago

How about adding a function to Node.

func (n *Node) MakeID(t time.Time, seq int64) (ID, error) {
    // ...
}