到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次循環開始於3月30日,而不是3月29日,與你的榜樣。據我所知,自2015年3月30日起爲2015年2月28日後30天,這與您的代碼得到的結果相同。
是'activated''datetime'參數和時間是'時間'?或者兩者都是'datetime'?舉個例子,你現在試圖從'2015年1月29日12:00 PM'到'Apr 29,2015 12:00 PM'多少個週期? – user3097405
'activated'和'time'都是時間對象。 'activated'是最初週期的開始。 '時間'是我試圖找到一個循環的時間。函數的結果是一個時間範圍(即2月28日,3月29日)。 – Stussa