如何获得长生不老药 [英] How to get previous month in elixir
本文介绍了如何获得长生不老药的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不使用elixir的程序包或库的情况下得到上个月?
How can I get the previous month without using a package or library in elixir?
例如,如果当前日期为 2018- 01-25
,我会得到 2017-12-25
。
或如果当前日期为 2018-03-31
,我将得到 2018-02-28
(2018年不是a年)
For example, if the current date is 2018-01-25
, I will get 2017-12-25
.
Or If the current date is 2018-03-31
, I will get 2018-02-28
(2018 is not a leap year)
推荐答案
@Sheharyar的答案差不多了,唯一需要区别的是减去两个月中最多天:
The answer by @Sheharyar is almost there, the only difference you need to subtract the maximum of days in both months:
defmodule Dating do
def previous_month(%Date{day: day} = date) do
days = max(day, (Date.add(date, -day)).day)
Date.add(date, -days)
end
end
适用于所有情况:
iex|1 ▶ Dating.previous_month(~D[2018-03-31])
#⇒ ~D[2018-02-28]
iex|2 ▶ Dating.previous_month(~D[2018-03-01])
#⇒ ~D[2018-02-01]
iex|3 ▶ Dating.previous_month(~D[2018-01-02])
#⇒ ~D[2017-12-02]
这篇关于如何获得长生不老药的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文