如何通过不同的间隔DATERANGE i循环? [英] How can i loop through a daterange with different intervals?

查看:133
本文介绍了如何通过不同的间隔DATERANGE i循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DATERANGE(从,到),我通过不同的时间间隔(每日,每周,每月,...)

I have a daterange (from, to) that i want loop through an different intervals (daily, weekly, monthly, ...)

如何通过这个dateranges i循环?

How can i loop through this dateranges?

更新

谢谢您的回答,我想出了以下内容:

Thanks for your answers, i came up with the following:

interval = 'week' # month, year
start = from
while start < to
  stop  = start.send("end_of_#{interval}")
  if stop > to
    stop = to
  end
  logger.debug "Interval from #{start.inspect} to #{stop.inspect}"
  start = stop.send("beginning_of_#{interval}")
  start += 1.send(interval)
end

此意愿通过一个时间范围与间隔一周,一个月或一年循环和尊重给定间隔的开始和结束。

This will loop through a date range with intervals week, month or year and respects the beginning and end of the given interval.

由于我没有提到这一点,在我的问题,我选用的把我推到正确的方向上的答案。

Since i did not mention this in my question i choosed the answer that pushed me into the right direction.

推荐答案

循环直到日期加上 1.day 1.week 1.month 大于日期?

Loop until the from date plus 1.day, 1.week, or 1.month is greater than the to date?

 > from = Time.now
 => 2012-05-12 09:21:24 -0400 
 > to = Time.now + 1.month + 2.week + 3.day
 => 2012-06-29 09:21:34 -0400 
 > tmp = from
 => 2012-05-12 09:21:24 -0400 
 > begin
?>   tmp += 1.week
?>   puts tmp
?> end while tmp <= to
2012-05-19 09:21:24 -0400
2012-05-26 09:21:24 -0400
2012-06-02 09:21:24 -0400
2012-06-09 09:21:24 -0400
2012-06-16 09:21:24 -0400
2012-06-23 09:21:24 -0400
2012-06-30 09:21:24 -0400
 => nil 

这篇关于如何通过不同的间隔DATERANGE i循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆