nresni
Retrieving the first and last day of previous month to build a query with a range date?
Hi,
I try to retrieve the first and last day of previous month to build a query with a range date.
Right now I’m doing this:
def foo(%DateTime{month: month, year: year} = current_date) do
# eg. 2019-01-01 00:00:00
start_date = %{current_date | month: month - 1, day: 1, hour: 00, minute: 00, second: 00}
days_of_month = DateTime.to_date(start_date) |> Date.days_in_month()
# eg. 2019-01-31 23:59:59
end_date = DateTime.add(start_date, (days_of_month - 1) * 86_400 + 86_399, :seconds)
...
end
For the moment I don’t handle the year change
, but before continuing I wanted to know if you had another way of doing it.
Thanks
Marked As Solved
LostKobrakai
Please don’t do such calculations on your own you’re bound to get into trouble with things like daylight-savings time switches or leap-seconds and things like that. Use a library like timex or calendar for calculations on datetimes.
Also Liked
rio517
Just in case someone stumbles across this, there are built-in functions to help with these calculations.
iex> Date.beginning_of_month(~D[2000-01-31])
~D[2000-01-01]
iex> Date.end_of_month(~D[2000-01-01])
~D[2000-01-31]
nresni
Oh yes, my bad, timex has everything I need.
Thanks
PJUllrich
Just another note that since Elixir 1.17, you can shift a date using Date.shift/2.
So, to get the beginning and end of the previous month, you could do:
beginning_of_previous_month =
Date.utc_today()
|> Date.beginning_of_month()
|> Date.shift(months: -1)
end_of_previous_month = Date.end_of_month(beginning_of_previous_month)







