Current epoch — epochtime.tools · A precision instrument for time
Try:

How a ULID is built

A ULID is 128 bits written as 26 characters of Crockford base32. Each character carries 5 bits. The alphabet is 0123456789ABCDEFGHJKMNPQRSTVWXYZ: it leaves out I, L, O and U so that IDs are hard to misread, and decoders accept lower case.

CharactersBitsField
1–1048Timestamp: milliseconds since 1970-01-01 UTC
11–2680Randomness

Because the time comes first and base32 keeps the order, ULIDs sort by creation time as plain strings. The first character can only be 0–7, since 10 characters hold 50 bits but the timestamp uses 48. The largest ULID time is in the year 10889.

Worked example

The ULID project's own example is 01ARYZ6S41TSV4RRFFQ69G5FAV.

  1. Take the first 10 characters: 01ARYZ6S41.
  2. Map each to its alphabet position (0, 1, 10, 24, 30, 31, 6, 25, 4, 1) and combine them as a base-32 number: 1469918176385.
  3. That is milliseconds since 1970: 2016-07-30T22:36:16.385Z.

Code

JavaScript

const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
function ulidTime(id) {
  let ms = 0;
  for (const ch of id.slice(0, 10).toUpperCase()) ms = ms * 32 + ALPHABET.indexOf(ch);
  return new Date(ms);
}
ulidTime('01ARYZ6S41TSV4RRFFQ69G5FAV').toISOString(); // '2016-07-30T22:36:16.385Z'

48 bits fit safely in a JavaScript number (the limit is 53 bits), so BigInt is not needed here.

Python

from datetime import datetime, timezone
ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'

def ulid_time(u: str) -> datetime:
    ms = 0
    for ch in u[:10].upper():
        ms = ms * 32 + ALPHABET.index(ch)
    return datetime.fromtimestamp(ms / 1000, timezone.utc)

ULID or UUID v7?

Both hold a 48-bit millisecond timestamp followed by random bits, and both sort by time. A UUID v7 fits UUID columns and tools that expect the 8-4-4-4-12 format. A ULID is shorter (26 characters instead of 36) and avoids characters that are easy to confuse. To read a UUID v7, use the UUID timestamp decoder.

Source: ULID specification (github.com/ulid/spec)

Last updated: