Skip to content

Instantly share code, notes, and snippets.

@5HT2
Last active December 18, 2020 19:23
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save 5HT2/c96ea58cf8acc06810e6a78493a92634 to your computer and use it in GitHub Desktop.
fun main() {
val snowflake = 563138570953687061 // 2019-04-03T23:11:37.924Z
println(snowflake.toInstant().prettyFormat())
}
/**
* @return an Epoch millisecond from a Discord Snowflake
* [offset] defaults to the first millisecond of 2015, or a "Discord Epoch"
*/
fun Long.fromDiscordSnowFlake(offset: Long = 1420070400000): Long {
return (this shr 22) + offset
}
/**
* @return an [Instant] from [epoch]
*/
fun Long.toInstant(epoch: Long = this.fromDiscordSnowFlake()): Instant {
return Instant.ofEpochMilli(epoch)
}
val formatter: DateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))
val replaceRegex = Regex("\\..*")
/**
* @return a "pretty" format lazily based off of ISO8601. Looks like "hh:mm:ss yyyy-mm-dd"
*/
fun Instant.prettyFormat(): String {
val split = formatter.format(this).split('T')
return split[1].replace(replaceRegex, " ") + split[0]
}

Playable example

https://pl.kotl.in/jDU6wYotK

What?

This is an extension function for turning Discord's Snowflake format into a Java Instant, and a few other functions.

Why?

I just needed an easy way to find readable time + dates from Discord Snowflakes, and docs weren't extremely clear as to how it works, as I overcomplicated it several times.

How?

Long.fromDiscordSnowFlake() will shift the Long 22 to the right, and then add the offset, which defaults to the first millisecond of 2015. This will give you an Epoch millisecond, which you can use in a Java Instant to format however you like. There is more detail on the docs

What's with the file name?

For some reason gists are alphabetically listed, and you can't change the order nor change the "base" file name which displays on your profile, it just chooses the first file.

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