diya
diya

Reputation: 7148

How to find the months in a year using Ruby

How to find the months in a year till this month.

months_of_year should return (2013-01-01, 2013-02-01, 2013-03-01, 2013-04-01, 2013-05-01) (assuming current month is 2013-05-01)

Upvotes: 1

Views: 83

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118299

require "date"
require "time"
(1..DateTime.now.month).map{|i| Date.new(DateTime.now.year,i,1).to_s }
#=> ["2013-01-01", "2013-02-01", "2013-03-01", "2013-04-01", "2013-05-01"]

Upvotes: 0

Andy Harvey
Andy Harvey

Reputation: 12663

This will give you an array of beginning of month dates for this year until today.

i=Date.today.beginning_of_year
a = []
while i <= Date.today
  a << i.beginning_of_month
  i=i + 1.month
end

Upvotes: 0

Hauleth
Hauleth

Reputation: 23586

You can create helper method:

def months_of_year(till = Date.today)
  (1..till.month).map { |m| Date.new(till.year, m) }
end

This will return array of dates of each 1st days from the beginning of year.

Upvotes: 3

Related Questions