Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous month in elixir

How can I get the previous month without using a package or library in elixir?

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)

like image 636
Dyey517 Avatar asked Nov 20 '18 14:11

Dyey517


2 Answers

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

Works for all cases:

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]
like image 153
Aleksei Matiushkin Avatar answered Sep 21 '22 08:09

Aleksei Matiushkin


Use Timex library

iex(1)> ~D[2018-01-25] |> Timex.shift(months: -1)
~D[2017-12-25]

iex(2)> ~D[2018-03-31] |> Timex.shift(months: -1)
~D[2018-02-28]
like image 42
denis.peplin Avatar answered Sep 21 '22 08:09

denis.peplin