下个月到达Elixir [英] Get next month in Elixir

查看:92
本文介绍了下个月到达Elixir的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的上一个问题中,Aleksei ,我试图查找给定日期的上个月。现在,我尝试做相反的事情:

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]






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


Note: Please don't suggest using a third-party Elixir package

推荐答案

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

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

这篇关于下个月到达Elixir的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆