How to get previous month in elixir

2020-03-26 05:37发布

问题:

How can I get the previous month without using a package or library in elixir?

For example, if the current date is 2018-01-25, I will get 2017-12-25. Or If the current date is 2018-03-31, I will get 2018-02-28 (2018 is not a leap year)

回答1:

The answer by @Sheharyar is almost there, the only difference you need to subtract the maximum of days in both months:

defmodule Dating do
  def previous_month(%Date{day: day} = date) do
    days = max(day, (Date.add(date, -day)).day)
    Date.add(date, -days)
  end
end

Works for all cases:

iex|1 ▶ Dating.previous_month(~D[2018-03-31])
#⇒ ~D[2018-02-28]
iex|2 ▶ Dating.previous_month(~D[2018-03-01])
#⇒ ~D[2018-02-01]
iex|3 ▶ Dating.previous_month(~D[2018-01-02])
#⇒ ~D[2017-12-02]


回答2:

Use Timex library

iex(1)> ~D[2018-01-25] |> Timex.shift(months: -1)
~D[2017-12-25]

iex(2)> ~D[2018-03-31] |> Timex.shift(months: -1)
~D[2018-02-28]