#Generating a list of months between two dates?

12 messages · Page 1 of 1 (latest)

ripe notch
#

We have Date.range/3 that allows steps to jump ahead, but this won't work on long time periods.
What I need is to be able to do for month <- Date.range(start, end) , by default it returns days. Is there a way of doing this without adding dependencies?

I could of course build my own function that takes the date and uses days_in_month to move ahead, but if there's a way of doing it that is already supported in the language that is of course preferable.

fair hemlock
#

You want to see how many months a date range covers? Can the range start at the end of the month or always at the beginning?

ripe notch
#

Always in the beginning

#

I made a function like this

defp months_in_range(date, end_date) do
  case Date.compare(date, end_date) do
    :lt ->
      [Date.add(date, 0) | months_in_range(Date.add(date, Date.days_in_month(date)), end_date)]

    _ ->
      []
  end
end
#

That way I can at least just get the month out of the Date

fair hemlock
#
Enum.reduce(Date.range(startdate, enddate), [], fn date, months ->
  if date.month not in months do
    [date.month | months]
  else
    months
  end
end)
``` I came up with this
ripe notch
#

I was thinking of using a reducer, but since it's over 5000 days it would be a lot of "not in"

fair hemlock
#

5000 is not a ton for the BEAM to handle, I wouldn't worry about it too much

#

Unless this is super perf critical part of your application

ripe notch
#

Not very perf critical, I mean your solution does end up looking a lot nicer, so thats a win for sure

#

However, I just realised, since it's multiple years I need to handle that

fair hemlock
#

Can make the date.month a tuple of month and year in my example, should work the same