Last active
May 26, 2017 05:55
-
-
Save sylph01/02cec0b86b241543cf9ee40e661433b9 to your computer and use it in GitHub Desktop.
Addition/Subtraction of Erlang Date with built-in functions only
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 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