问题
In my last question answered by Aleksei, I was trying to find the previous month for a given date. Now I'm trying to do the opposite:
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
Though the code works correctly, I'm hoping there's a better way to do this:
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]
Note: Please don't suggest using a third-party Elixir package
回答1:
Your approach is correct, though you can use Date module's methods to make it more concise and a bit easier to read & understand:
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
来源:https://stackoverflow.com/questions/53512997/get-next-month-in-elixir