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

I need to scroll through all the days and months of the last couple of decades numerically, and also have the name of the month and day for each date. Obviously, several looping cycles can accomplish this, but I would like to know the most concise way, like a ruby, to accomplish this.

Essentially, I will need a conclusion similar to this for every day over the past X years:

January 3, 2011 and 1/3/2011

What is the cleanest approach?

+4
source share
3 answers

Dates can work as a range, so it's pretty 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 that I was not lucky with images with unread percentage formats such as %-d on Windows, but if the above does not work and you want them to be blank in this environment, you can remove the dash and use your own workarounds.)

+18
source

Given start_date and end_date :

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

as David said this is possible due to Date # succ . You can use Date#strftime to get the date in any format you want.

+4
source

See if you can build a range where min and max are Date objects, then call .each in the range. If the Date object supports the succ method, this should work.

+2
source

Source: https://habr.com/ru/post/1396001/


All Articles