我有一个应用程序可以跟踪每个周期的容量(其中一个周期是从激活开始的几个月)。例如:
- 2015 年 1 月 29 日中午 12:00 - 2015 年 2 月 28 日中午 12:00(第 1 周期)
- 2015 年 2 月 28 日中午 12:00 - 2015 年 3 月 29 日中午 12:00(周期 #2)
- 2015 年 3 月 29 日中午 12:00 - 2015 年 4 月 29 日中午 12:00(周期 #3)
- ...
被跟踪的信息是“激活”日期(即初始周期的开始)。有没有一种计算给定日期的周期(范围)的好方法?我当前的实现有效但看起来很浪费(必须循环到日期):
def period(activated, time)
cycles = 0
cycles = cycles.next while activated + cycles.next.months < time
return (activated + cycles.months)..(activated + cycles.next.months)
end
最佳答案
到 Rails,1.month
is 30.days
,所以实际上,只需一点数学,您就可以在没有所有迭代的情况下做到这一点:
def period(activated, time)
days = (time - activated).to_i
cycle_idx = days / 30
cycle_start = activated + cycle_idx * 30
cycle_start..(cycle_start + 30)
end
让我分解一下:
activated = DateTime.parse('Jan 29, 2015 12:00PM') # => #<DateTime: 2015-01-29T12:00:00+00:00 ...>
time = DateTime.parse('Apr 15, 2015 6:00PM') # => #<DateTime: 2015-04-30T12:00:00+00:00 ...>
# Get the number of days between `activated` and `time`.
days = (time - activated).to_i # => (305/4).to_i => 76
# Divide by 30 to get the cycle number (0-based).
cycle_idx = days / 30 # => 2
# Multiply the cycle number by 30 and add it to `activated` to get
# the beginning of the cycle.
cycle_start = activated + cycle_idx * 30 # => #<DateTime: 2015-03-30T12:00:00+00:00 ...>
# Add 30 more to get the end of the cycle.
cycle_start..(cycle_start + 30)
# => #<DateTime: 2015-03-30T12:00:00+00:00 ...>
# ..#<DateTime: 2015-04-29T12:00:00+00:00 ...>
您会像我一样注意到,第三个周期从 3 月 30 日开始,而不是 3 月 29 日,这与您的示例不同。据我所知,这与您使用代码得到的结果相同,因为 2015 年 3 月 30 日是 2015 年 2 月 28 日之后的 30 天。
关于ruby-on-rails - 使用 Ruby/Rails 在当前周期中寻找容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324894/