Skip to content

Instantly share code, notes, and snippets.

@kawarimidoll
Created July 23, 2022 22:59
Show Gist options
  • Save kawarimidoll/a5e62ac2dab54a83285877d39f30541d to your computer and use it in GitHub Desktop.
Save kawarimidoll/a5e62ac2dab54a83285877d39f30541d to your computer and use it in GitHub Desktop.
generate three characters timestamp that is sortable
export function threeCharactersTimestamp(date?: Date) {
if (!date) {
date = new Date();
}
const [h, m, s] = [date.getHours(), date.getMinutes(), date.getSeconds()];
// min & sec eatch 4 seconds
const ms = Math.floor((m * 60 + s) / 4);
const [m2, s2] = [Math.floor(ms / 30), ms % 30];
// convert to three-characters-timestamp
// l, 1 and 0 are not used to avoid confusing with i and o
const lowers = [..."abcdefghijkmnopqrstuvwxyz"];
const hChar = lowers[h];
const alnum = [..."2345789", ...lowers.filter((c) => c != hChar)];
const mChar = alnum[m2];
const sChar = alnum.filter((c) => c != mChar)[s2];
return date.toLocaleDateString("ja-JP", {
year: "numeric",
month: "2-digit",
day: "2-digit",
}).replaceAll("/", "") + "-" + hChar + mChar + sChar;
}
// console.log(threeCharactersTimestamp());
// -> generate current timestamp
// console.log(threeCharactersTimestamp(new Date('2022-05-01T10:33:22')));
// -> 20220501-kjq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment