Skip to content

Instantly share code, notes, and snippets.

@sylph01
Last active May 26, 2017 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sylph01/02cec0b86b241543cf9ee40e661433b9 to your computer and use it in GitHub Desktop.
Save sylph01/02cec0b86b241543cf9ee40e661433b9 to your computer and use it in GitHub Desktop.
Addition/Subtraction of Erlang Date with built-in functions only
defmodule DateArith do
def next_month({y, 12, d}), do: {y + 1, 1, d}
def next_month({y, m, d}), do: {y, m + 1, d}
def previous_month({y, 1, d}), do: {y - 1, 12, d}
def previous_month({y, m, d}), do: {y, m - 1, d}
def add_month({y, m, d}, ms) do
{
y + div(m + ms - 1, 12),
rem12(m + ms),
d
}
end
def sub_month(date, 0), do: date
def sub_month({y, m, d}, ms) do
{
y + div(m - ms, 12) - 1,
rem12(m - ms),
d
}
end
defp rem12(m) do
rem = rem(m, 12)
cond do
rem == 0 -> 12
rem < 0 -> rem + 12
rem > 0 -> rem
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment