如何在 Elixir 中实现 Date.add(date, n, :month)

Cha*_*gwu 6 date elixir

如果能将它放在标准 Elixir 库中就好了,但我们没有。

Date.add(date, n, :month) # where n could be +/-
Run Code Online (Sandbox Code Playgroud)

你会如何实施这个?

这看起来是一个很好的起点:https ://stackoverflow.com/a/53407676/44080

leg*_*cia 3

您可以使用Timex 实现

  defp shift_by(%NaiveDateTime{:year => year, :month => month} = datetime, value, :months) do
    m = month + value
    shifted =
      cond do
        m > 0 ->
          years = div(m - 1, 12)
          month = rem(m - 1, 12) + 1
          %{datetime | :year => year + years, :month => month}
        m <= 0 ->
          years = div(m, 12) - 1
          month = 12 + rem(m, 12)
          %{datetime | :year => year + years, :month => month}
      end

    # If the shift fails, it's because it's a high day number, and the month
    # shifted to does not have that many days. This will be handled by always
    # shifting to the last day of the month shifted to.
    case :calendar.valid_date({shifted.year,shifted.month,shifted.day}) do
      false ->
        last_day = :calendar.last_day_of_the_month(shifted.year, shifted.month)
        cond do
          shifted.day <= last_day ->
            shifted
          :else ->
            %{shifted | :day => last_day}
        end
      true ->
        shifted
    end
  end
Run Code Online (Sandbox Code Playgroud)

Timex使用 MIT 许可证,因此您应该能够将其合并到几乎任何项目中。