我正在尝试创建季度间隔,类似于我使用以下代码创建每月间隔的方式
[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))间隔应为1-3月Q1、4-6月Q2、7-9月Q3、10-12月Q4。我可以通过将月份向下舍入到季度的第一天并递增三个月来实现这一点,但我想知道是否有内置的功能来做季度。
发布于 2018-01-11 06:02:33
如果你总是想要所提供年份的季度数,你可以这样做:
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))(这将返回["2018-01", "2018-04", "2018-07", "2018-10"])
顺便说一句,您实际上不需要在原始代码行中使用with_step/2。您只需要在更改原始步骤时使用该函数。您可以直接在new/1中声明该步骤,就像我在上面的示例中所做的那样。
虽然Timex不会自动构建季度间隔,但它确实有一种方法来获取日期所属的季度。如果需要从当前季度开始,您可以这样做:
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))发布于 2018-01-11 06:27:34
多亏了Mario,他帮助简化了代码。下面是我最终完成的代码
def periods(start_date, end_date, "quarter") do
start_date = Timex.beginning_of_quarter(start_date)
[from: start_date, until: end_date, right_open: false, step: [months: 3]]
|> Interval.new
|> Enum.map(&calculate_quarter(&1))
end
def calculate_quarter(date), do: "Q#{Timex.quarter(date)} #{Timex.format!(date, "%Y", :strftime)}"https://stackoverflow.com/questions/48195509
复制相似问题