Skip to content

Instantly share code, notes, and snippets.

@claudijo
Created November 29, 2019 12:55
Show Gist options
  • Save claudijo/9d38ed45842cd28d8ae57d7d7a03c7ab to your computer and use it in GitHub Desktop.
Save claudijo/9d38ed45842cd28d8ae57d7d7a03c7ab to your computer and use it in GitHub Desktop.
Date from ulid string
// Reference https://github.com/ulid/spec
const alphabet = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
function dateFromUlid(ulid) {
let timestamp = 0;
const decodedTimestamp = ulid.substring(0, 10).toUpperCase();
for (let i = 0; i < decodedTimestamp.length; i++) {
const char = decodedTimestamp.charAt(i);
const multiplier = alphabet.indexOf(char);
const exponent = (9 - i);
timestamp += (Math.pow(32, exponent)) * multiplier;
}
return new Date(timestamp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment