Date start and end of all months

How to automatically generate in ruby start and end date of each
month
taking account of the year

Thank you

Simon E. wrote in post #1171001:

How to automatically generate in ruby start and end date of each
month

(1…12).each {|month|
p [Time.new(2015,month,1),
(month<12 ? Time.new(2015,month+1,1) : Time.new(2016,1,1))-3600]
}
[2015-01-01 00:00:00 +0100, 2015-01-31 00:00:00 +0100]
[2015-02-01 00:00:00 +0100, 2015-02-28 00:00:00 +0100]
[2015-03-01 00:00:00 +0100, 2015-03-31 00:00:00 +0200]
[2015-04-01 00:00:00 +0200, 2015-04-30 00:00:00 +0200]
[2015-05-01 00:00:00 +0200, 2015-05-31 00:00:00 +0200]
[2015-06-01 00:00:00 +0200, 2015-06-30 00:00:00 +0200]
[2015-07-01 00:00:00 +0200, 2015-07-31 00:00:00 +0200]
[2015-08-01 00:00:00 +0200, 2015-08-31 00:00:00 +0200]
[2015-09-01 00:00:00 +0200, 2015-09-30 00:00:00 +0200]
[2015-10-01 00:00:00 +0200, 2015-10-31 00:00:00 +0100]
[2015-11-01 00:00:00 +0100, 2015-11-30 00:00:00 +0100]
[2015-12-01 00:00:00 +0100, 2015-12-31 00:00:00 +0100]

or
(1…12).each {|m|
p [Time.new(2015,m,1),Time.new(2015+m/12,(m-1)%11+1,1)-246060]
}

I’d rather use class Date for this.

require ‘date’

def first_and_last(year = Date.today.year)
return to_enum(:first_and_last, year) unless block_given?

12.times do |m|
d = Date.new year, m + 1, 1
yield d - 1 unless m == 0
yield d
end

yield Date.new(year, 12, 31)
end

Thank you very much for help

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs