EDA.Snowflake (EDA v0.3.0)

Copy Markdown View Source

Utilities for extracting timestamps from Discord snowflake IDs.

Discord snowflakes encode a timestamp in their upper bits:

timestamp_ms = (snowflake >>> 22) + discord_epoch

Where discord_epoch is 1_420_070_400_000 (2015-01-01T00:00:00Z).

Summary

Functions

Returns the age of a snowflake in seconds (as a float).

Returns the creation time of a snowflake as a UTC DateTime.

Returns the Discord epoch (2015-01-01T00:00:00Z) in Unix milliseconds.

Generates a snowflake ID from a DateTime.

Extracts the Unix timestamp in milliseconds from a snowflake ID.

Functions

age(snowflake)

@spec age(integer() | String.t()) :: float()

Returns the age of a snowflake in seconds (as a float).

Examples

iex> EDA.Snowflake.age(175928847299117063) > 0
true

created_at(snowflake)

@spec created_at(integer() | String.t()) :: DateTime.t()

Returns the creation time of a snowflake as a UTC DateTime.

Examples

iex> EDA.Snowflake.created_at(175928847299117063)
~U[2016-04-19 01:00:01.796Z]

discord_epoch()

@spec discord_epoch() :: integer()

Returns the Discord epoch (2015-01-01T00:00:00Z) in Unix milliseconds.

from_datetime(dt)

@spec from_datetime(DateTime.t()) :: integer()

Generates a snowflake ID from a DateTime.

All worker/process/increment bits are set to zero. This is useful for comparison and filtering (e.g. "messages older than 14 days"), not for creating real Discord entities.

Examples

iex> dt = EDA.Snowflake.created_at(EDA.Snowflake.from_datetime(~U[2024-01-01 00:00:00Z]))
iex> DateTime.truncate(dt, :second)
~U[2024-01-01 00:00:00Z]

timestamp(snowflake)

@spec timestamp(integer() | String.t()) :: integer()

Extracts the Unix timestamp in milliseconds from a snowflake ID.

Examples

iex> EDA.Snowflake.timestamp(175928847299117063)
1461015601796