Skip to content

Instantly share code, notes, and snippets.

@benhatsor
Last active February 10, 2024 15:47
Show Gist options
  • Save benhatsor/b40d83acafa7bae1ed70eb76a2ed51a6 to your computer and use it in GitHub Desktop.
Save benhatsor/b40d83acafa7bae1ed70eb76a2ed51a6 to your computer and use it in GitHub Desktop.
Generate a unique ID based on the current time. Note: If you need a truly unique ID, use something like the JS Crypto API instead.
// Both numbers and letters
function mixedID() {
var now = new Date();
timestamp = now.getFullYear().toString();
timestamp += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString();
timestamp += ((now.getDate < 10) ? '0' : '') + now.getDate().toString();
timestamp += now.getHours().toString();
timestamp += now.getMinutes().toString();
timestamp += now.getSeconds().toString();
timestamp += now.getMilliseconds().toString();
id = 'a';
for (var i = 0; i < timestamp.length; i++) {
id = id + String.fromCharCode(97 + Number(timestamp[i])) + (Number(timestamp[i]) + 5);
}
return id
}
// Letters
function baseID() {
var now = new Date();
timestamp = now.getFullYear().toString();
timestamp += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString();
timestamp += ((now.getDate < 10) ? '0' : '') + now.getDate().toString();
timestamp += now.getHours().toString();
timestamp += now.getMinutes().toString();
timestamp += now.getSeconds().toString();
timestamp += now.getMilliseconds().toString();
id = '';
for (var i = 0; i < timestamp.length; i++) {
id = id + String.fromCharCode(97 + Number(timestamp[i]));
}
return id
}
// Numbers
function numID() {
var now = new Date();
id = now.getFullYear().toString();
id += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString();
id += ((now.getDate < 10) ? '0' : '') + now.getDate().toString();
id += now.getHours().toString();
id += now.getMinutes().toString();
id += now.getSeconds().toString();
id += now.getMilliseconds().toString();
return Number(id)
}
@orefalo
Copy link

orefalo commented Oct 9, 2020

Neat
What if two generations happen on the same ms? -> same id?
Differences with Ulid? KSUID?
Any boundary limits?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment