A universally-unique, lexicographically-sortable, identifier generator
78
Functions for encoding and decoding timestamps in ULID format, enabling extraction of creation time from any ULID and custom timestamp encoding.
Extracts the timestamp from a ULID string, returning the original millisecond timestamp used during generation.
/**
* Decode time from a ULID
* @param id - The ULID string to decode
* @returns The decoded timestamp in milliseconds since Unix epoch
* @throws ULIDError if the ULID is malformed or contains invalid characters
*/
function decodeTime(id: ULID): number;Usage Examples:
import { decodeTime, ulid } from "ulid";
// Generate a ULID and extract its timestamp
const id = ulid();
const timestamp = decodeTime(id);
const createdAt = new Date(timestamp);
console.log(`ULID ${id} was created at ${createdAt.toISOString()}`);
// Decode timestamp from existing ULID
const existingId = "01HNZX8JGFACFA36RBXDHEQN6E";
const originalTime = decodeTime(existingId); // 1469918176385
// Use with specific ULID
try {
const time = decodeTime("01ARYZ6S41TSV4RRFFQ69G5FAV");
console.log(new Date(time)); // Original creation date
} catch (error) {
console.error("Invalid ULID:", error.message);
}Error Conditions:
ULIDError with code DecodeTimeValueMalformed if ULID length is incorrectULIDError with code DecodeTimeInvalidCharacter if ULID contains invalid Base32 charactersULIDError with code DecodeTimeValueMalformed if decoded timestamp exceeds maximum valueEncodes a timestamp into ULID time format using Crockford Base32 encoding.
/**
* Encode the time portion of a ULID
* @param now - The timestamp to encode (milliseconds since Unix epoch)
* @param len - Length to generate (default: TIME_LEN = 10)
* @returns The encoded time string
* @throws ULIDError for invalid timestamp values
*/
function encodeTime(now: number, len?: number): string;Usage Examples:
import { encodeTime, TIME_LEN } from "ulid";
// Encode current timestamp
const now = Date.now();
const encoded = encodeTime(now); // "01HNZXD07M"
// Encode specific timestamp
const specificTime = 1469918176385;
const timeStr = encodeTime(specificTime); // "01ARYZ6S41"
// Encode with custom length (advanced usage)
const shortTime = encodeTime(now, 8); // Shorter time encoding
// Use with Date objects
const futureDate = new Date("2030-01-01T00:00:00Z");
const futureEncoded = encodeTime(futureDate.getTime());Error Conditions:
ULIDError with code EncodeTimeValueMalformed if timestamp is NaN or not an integerULIDError with code EncodeTimeNegative if timestamp is negativeULIDError with code EncodeTimeSizeExceeded if timestamp exceeds TIME_MAX (2^48 - 1)Time Format Details:
0123456789ABCDEFGHJKMNPQRSTVWXYZconst TIME_LEN: number; // 10 - Standard length of time portion
const TIME_MAX: number; // 281474976710655 - Maximum timestamp value (2^48 - 1)Install with Tessl CLI
npx tessl i tessl/npm-ulidevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10