Created
November 29, 2019 12:55
-
-
Save claudijo/9d38ed45842cd28d8ae57d7d7a03c7ab to your computer and use it in GitHub Desktop.
Date from ulid string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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