在我上次由question回答的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软件包
答案 0 :(得分:3)
您的方法是正确的,尽管您可以使用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