KSUID decoder
A KSUID stores seconds since 2014-05-13 in its first 4 bytes. Paste one to read the time and payload.
Try:
KSUID layout
KSUID stands for K-Sortable Unique IDentifier. Segment created it, and it is used in their tools and in other systems that want time-sortable IDs.
| Bytes | Field |
|---|---|
| 0–3 | Timestamp: seconds since the KSUID epoch, big-endian, unsigned |
| 4–19 | Payload: 128 random bits |
The 20 bytes are written as 27 base62 characters (0–9, A–Z, a–z). The KSUID epoch is Unix time 1400000000, which is 2014-05-13T16:53:20Z. Moving the start forward lets the 32-bit field last until about the year 2150.
Worked example
Segment's README decodes 0ujtsYcgvSTl8PAuAdqWYSMnLOv:
- Decode the 27 characters from base62 into 20 bytes.
- The first 4 bytes are
0669F7EF=107608047seconds after the KSUID epoch. - Add
1400000000: Unix time1507608047, which is 2017-10-10T04:00:47Z (9:00:47 PM PDT on 9 October, as the README shows).
Code
JavaScript
const B62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
function ksuidTime(id) {
let v = 0n;
for (const ch of id) v = v * 62n + BigInt(B62.indexOf(ch));
const seconds = Number(v >> 128n) + 1400000000;
return new Date(seconds * 1000);
}
ksuidTime('0ujtsYcgvSTl8PAuAdqWYSMnLOv').toISOString(); // '2017-10-10T04:00:47.000Z'
Go (segmentio/ksuid)
id, _ := ksuid.Parse("0ujtsYcgvSTl8PAuAdqWYSMnLOv")
fmt.Println(id.Time().UTC()) // 2017-10-10 04:00:47 +0000 UTC
Last updated: