Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Elixir time conversion module for converting milliseconds or seconds to a readable format.
defmodule TimeConvert do
@minute 60
@hour @minute*60
@day @hour*24
@week @day*7
@divisor [@week, @day, @hour, @minute, 1]
def to_str(time) do
to_str(time, :ms)
end
def to_str(time, :ms) do
ms_to_str(time)
end
def to_str(time, :seconds) do
sec_to_str(time)
end
defp sec_to_str(sec) do
{_, [s, m, h, d, w]} =
Enum.reduce(@divisor, {sec,[]}, fn divisor,{n,acc} ->
{rem(n,divisor), [div(n,divisor) | acc]}
end)
["#{w} wk", "#{d} d", "#{h} hr", "#{m} min", "#{s} sec"]
|> Enum.reject(fn str -> String.starts_with?(str, "0") end)
|> Enum.join(", ")
end
defp ms_to_str(ms), do: (ms / 1_000) |> sec_to_str()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.