Ahmad Arshi
Ahmad Arshi

Reputation: 83

How to create dates of a particular month

I want to generate all the dates of a particular month starting from the 1st of that month to the 30 or 31st of that month with out using a trivial for loop:

for i in 1..Time.days_in_month(Date.today.month, Date.today.year)
  date = Date.new(y, m, i)
end

I was getting dates like this but I'm not supposed to use this trivial for loop.

Upvotes: 1

Views: 1009

Answers (2)

steenslag
steenslag

Reputation: 80085

(Plain Ruby) The Date class uses negative numbers as a way of counting from the end (like in Arrays):

require "date"

today = Date.today
m, y  = today.month, today.year
p (Date.new(y,m,1) .. Date.new(y,m,-1)).to_a

Upvotes: 2

calebkm
calebkm

Reputation: 1033

Although there are quite a few ways you could accomplish this, one way would be to use a Ruby Range combined with the Time#beginning_of_month and Time#end_of_month methods to generate an object that contains all of the days of the month and then convert it into an array:

(Date.today.beginning_of_month..Date.today.end_of_month).to_a
=> [Fri, 01 Nov 2019, Sat, 02 Nov 2019, Sun, 03 Nov 2019, Mon, 04 Nov 2019, Tue, 05 Nov 2019, Wed, 06 Nov 2019, ...., Fri, 29 Nov 2019, Sat, 30 Nov 2019]

Another option would be to use the Time#all_month helper which is as simple as:

Date.today.all_month.to_a
=> [Fri, 01 Nov 2019, Sat, 02 Nov 2019, Sun, 03 Nov 2019, Mon, 04 Nov 2019, Tue, 05 Nov 2019, Wed, 06 Nov 2019, ...., Fri, 29 Nov 2019, Sat, 30 Nov 2019]

Upvotes: 7

Related Questions