Time#upto September 17th, 2008
In of of our applications I had to create an XML file to generate a time-based graph. For this I needed the time in certain intervals, for example from 1 year ago to now with an interval of 1 day. I looked around but there were no obvious solutions, so I came up with my own!
# Rails convenience functions are used in the examples >> 1.week.ago.upto(:now) { |day| puts day } Wed Sep 10 14:58:42 +0200 2008 Thu Sep 11 14:58:42 +0200 2008 Fri Sep 12 14:58:42 +0200 2008 Sat Sep 13 14:58:42 +0200 2008 Sun Sep 14 14:58:42 +0200 2008 Mon Sep 15 14:58:42 +0200 2008 Tue Sep 16 14:58:42 +0200 2008 Wed Sep 17 14:58:42 +0200 2008 >> 5.hours.ago.upto(:now, 1.hour) { |day| puts day } Wed Sep 17 09:59:24 +0200 2008 Wed Sep 17 10:59:24 +0200 2008 Wed Sep 17 11:59:24 +0200 2008 Wed Sep 17 12:59:24 +0200 2008 Wed Sep 17 13:59:24 +0200 2008 Wed Sep 17 14:59:24 +0200 2008 >> 5.hours.ago.upto(1.hour.ago, 1.hour) { |day| puts day } Wed Sep 17 09:59:58 +0200 2008 Wed Sep 17 10:59:58 +0200 2008 Wed Sep 17 11:59:58 +0200 2008 Wed Sep 17 12:59:58 +0200 2008 Wed Sep 17 13:59:58 +0200 2008
The upto function does all the stupid time logic for you! If you want to use this function yourself, this is the code:
class Time def upto(date, step = 86400) # 1.day time = self.dup until_time = case date when :now Time.now else date end until time > until_time yield time time += step end end end