Skip to content

Instantly share code, notes, and snippets.

@k456
Created August 3, 2012 04:52
Show Gist options
  • Save k456/3244482 to your computer and use it in GitHub Desktop.
Save k456/3244482 to your computer and use it in GitHub Desktop.
ruby Date#step_by_month
class Date
def step_by_month(to_date, step=1)
date = self
op = %w(- <= >=)[step <=> 0]
while date.__send__(op, to_date)
yield(date)
date >>= step
end
end
end
@k456
Copy link
Author

k456 commented Apr 24, 2014

require "date"
require "custom-date-step-by-month"

date = Date.new(2014, 1, 1)
date.step_by_month(Date.new(2015, 1, 1)) do |d|
  puts d
end
#2014-01-01
#2014-02-01
#2014-03-01
#2014-04-01
#2014-05-01
#2014-06-01
#2014-07-01
#2014-08-01
#2014-09-01
#2014-10-01
#2014-11-01
#2014-12-01
#2015-01-01


date = Date.new(2014, 1, 1)
date.step_by_month(Date.new(2013, 1, 1), -1) do |d|
  puts d
end
#2014-01-01
#2013-12-01
#2013-11-01
#2013-10-01
#2013-09-01
#2013-08-01
#2013-07-01
#2013-06-01
#2013-05-01
#2013-04-01
#2013-03-01
#2013-02-01
#2013-01-01

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment