jamesmintram
Get date N months/years in the past
I have been reading the docs for Elixir’s Date/DateTime libraries but I cannot find a way to calculate a date which is either N months or N years before/after a particular date.
Date.add/2 appears to only accept days.
DateTime.add/3 will only accept “up to” :seconds
Can someone point me in the right direction?
Most Liked
kip
ex_cldr_calendars also provides the ability to add date parts to dates: Cldr.Calendar — Cldr Calendars v1.19.0
iex> Cldr.Calendar.minus ~D[2019-03-01], :days, 1
~D[2019-02-28]
iex> Cldr.Calendar.minus ~D[2019-03-01], :months, 1
~D[2019-02-01]
iex> Cldr.Calendar.minus ~D[2019-03-01], :quarters, 1
~D[2018-12-01]
iex> Cldr.Calendar.minus ~D[2019-03-01], :years, 1
~D[2018-03-01]
kip
@josevalim, there’s no CLDR dependency on this part - its all straight Calendar callbacks.
The only part that is tricky is what to do with something like Calendar.shift ~[2016-02-29], :year, 1. It is an invalid result?
In my implementation I have an option :coerce to force a valid date at the end of the target month. I’ve never liked it. Suggestions very welcome on how to handle this.
Happy to draft a PR for this, its not very complicated other than that issue.
josevalim
I would love to have this feature in Elixir. To me it is really the last pending feature in the Calendar module. It seems it is a simple contract on a function called “plus”, which I would call “shift” instead.
@kip, how are the rules generated in your case? Automatically from CLDR? Is there a way we could see the rules converted to Elixir code for the ISO calendar?
Thank you!
rhcarvalho
For future reference, the many shift functions discussed in this thread landed in Elixir v1.17.0 (tagged Jun 12, 2024).
Changelog notes: Changelog for Elixir v1.17 — Elixir v1.17.0
hubertlepicki
I generally use third party library for this, although maybe it’s possible withing standard library these days, but I default to Timex.shift from timex library:







