Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create quarterly interval with timex and elixir

Tags:

elixir

I'm trying to create quarterly intervals similar to how I create monthly intervals with this code

[from: start_date, until: end_date, right_open: false]
|> Timex.Interval.new()
|> Timex.Interval.with_step([months: 1])
|> Enum.map(&Timex.format!(&1, "%Y-%m", :strftime))

The intervals should be Jan-Mar Q1, Apr-Jun Q2, Jul-Sep Q3, Oct-Dec Q4. I could accomplish this by rounding the month down to the first date of the quarter and increment by three months, but I am wondering if there is built in functionality to do quarters.

like image 718
Michael St Clair Avatar asked Sep 15 '25 01:09

Michael St Clair


1 Answers

If you always want the quarters from the beggining of the provided year, you could do this:

Timex.Interval.new(from: Timex.beginning_of_year(provided_date),
                   until: [years: 1],
                   right_open: false,
                   step: [months: 3])
|> Enum.map(&Timex.format!(&1, "%Y-%m", :strftime))

(this returns ["2018-01", "2018-04", "2018-07", "2018-10"])

BTW you don't actually need to use with_step/2 in your original line. You only need to use that function when you're changing the original step. You can declare the step directly in new/1 like I've done in the above example.

While Timex won't automatically build quarter intervals, it does have a way to get the quarter that a date belongs to. You could do this if you need to start from the current quarter:

Timex.Interval.new(from: Timex.beginning_of_quarter(provided_date),
               until: [years: 1],
               right_open: false,
               step: [months: 3])
|> Enum.map(&Timex.format!(&1, "%Y-%m", :strftime))
like image 113
Mario Avatar answered Sep 17 '25 20:09

Mario