Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop numerically + month and day over the past X years?

Tags:

ruby

I need to loop through all of the days and months for the past couple decades numerically as well as to have the name of the month and day for each date. Obviously a few series of loops can accomplish this, but I wanted to know the most concise ruby-like way to accomplish this.

Essentially I'd need output like this for each day over the past X years:

3 January 2011 and 1/3/2011

What's the cleanest approach?

like image 625
ylluminate Avatar asked Nov 29 '22 09:11

ylluminate


2 Answers

Dates can work as a range, so it's fairly easy to iterate over a range. The only real trick is how to output them as a formatted string, which can be found in the Date#strftime method, which is documented here.

from_date = Date.new(2011, 1, 1)
to_date   = Date.new(2011, 1, 10)

(from_date..to_date).each { |d| puts d.strftime("%-d %B %Y and %-m/%-d/%Y") }

# => 1 January 2011 and 1/1/2011
# => 2 January 2011 and 1/2/2011
# => ...
# => 9 January 2011 and 1/9/2011
# => 10 January 2011 and 1/10/2011

(Note: I recall having some bad luck a ways back with unpadded percent formats like %-d in Windows, but if the above doesn't work and you want them unpadded in that environment you can remove the dash and employ your own workarounds.)

like image 96
brymck Avatar answered Dec 23 '22 10:12

brymck


Given start_date & end_date:

(start_date..end_date).each do |date|
  # do things with date
end

as David said, this is possible because of Date#succ. You can use Date#strftime to get the date in any format you'd like.

like image 40
Andrew Marshall Avatar answered Dec 23 '22 09:12

Andrew Marshall