-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
convert.js
34 lines (28 loc) · 1.05 KB
/
convert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
export const DISCORD_EPOCH = 1420070400000
// Converts a snowflake ID string into a JS Date object using the provided epoch (in ms), or Discord's epoch if not provided
export function convertSnowflakeToDate(snowflake, epoch = DISCORD_EPOCH) {
// Convert snowflake to BigInt to extract timestamp bits
// https://discord.com/developers/docs/reference#snowflakes
const milliseconds = BigInt(snowflake) >> 22n
return new Date(Number(milliseconds) + epoch)
}
// Validates a snowflake ID string and returns a JS Date object if valid
export function validateSnowflake(snowflake, epoch) {
if (!Number.isInteger(+snowflake)) {
throw new Error(
"That doesn't look like a snowflake. Snowflakes contain only numbers."
)
}
if (snowflake < 4194304) {
throw new Error(
"That doesn't look like a snowflake. Snowflakes are much larger numbers."
)
}
const timestamp = convertSnowflakeToDate(snowflake, epoch)
if (Number.isNaN(timestamp.getTime())) {
throw new Error(
"That doesn't look like a snowflake. Snowflakes have fewer digits."
)
}
return timestamp
}