Created
January 17, 2018 02:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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