获取下个月的 Elixir

Get next month in Elixir

在我的最后一个 answered by Aleksei 中,我试图找到给定日期的上个月。现在我正在尝试做相反的事情:

defmodule Dating do
  def next_month(%Date{year: year, month: month, day: day} = date) do
    first_day_of_next_month = Date.add(date, Calendar.ISO.days_in_month(year, month) - day + 1)
    %{year: year, month: month} = first_day_of_next_month
    Date.add(first_day_of_next_month, min(day, Calendar.ISO.days_in_month(year, month)) - 1)
  end
end

虽然代码工作正常,但我希望有更好的方法来做到这一点:

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

注意:请不要建议使用第三方 Elixir 包

您的方法是正确的,尽管您可以使用 Date 模块的方法使其更简洁,更易于阅读和理解:

defmodule Dating do
  def next_month(%Date{day: day} = date) do
    days_this_month = Date.days_in_month(date)
    first_of_next   = Date.add(date, days_this_month - day + 1)
    days_next_month = Date.days_in_month(first_of_next)

    Date.add(first_of_next, min(day, days_next_month) - 1)
  end
end