Skip to content

Instantly share code, notes, and snippets.

@brayhoward
Created January 17, 2018 02:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brayhoward/0637da480877af5d64fe0d25e6d1772e to your computer and use it in GitHub Desktop.
Save brayhoward/0637da480877af5d64fe0d25e6d1772e to your computer and use it in GitHub Desktop.
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