如何在长生不老药中获得上个月 [英] How to get previous month in elixir

查看:13
本文介绍了如何在长生不老药中获得上个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用 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年不是闰年)

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 的答案就差不多了,唯一的区别是你需要减去两个月的最大天数:p>

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屋!

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