Gareth Burrows
Gareth Burrows

Reputation: 1182

Getting the first and last day of a month in ruby from partial string

I have a table with a column for year, which is an integer, and a column for month, which again is an integer. I need (in ruby) to be able to end up with a start_date and an end_date for each row.

So from the first row, where the year is 2016 and the month is 1, I need to get start_date = 01/01/2016 and end date = 31/01/2016. i know I can get them in ruby with beginning_of_month and end_of_month, but I need to get to a date first?

I'm getting lost in Date.parse and Date.strptime, and could really do with someone explaining it. Presumably I cannot get a date to begin with because I don't actually have a day to work with !

help :)

Upvotes: 2

Views: 1925

Answers (3)

steenslag
steenslag

Reputation: 80065

require "date"
year_months = [[2016, 5], [2015, 6]]

dates = year_months.map do |y, m|
  [Date.new(y, m, 1), Date.new(y, m, -1)] # -1 is last day of month
end

Upvotes: 3

Matouš Borák
Matouš Borák

Reputation: 15944

You can simply parse the date as if it were the 1st day of the month:

 year = 2016
 month = 6
 d = Date.parse("#{year}-#{month}-01")
 # => Wed, 01 Jun 2016

And then calculate the last day using end_of_month method, just as you proposed:

 d.end_of_month
 # => Thu, 30 Jun 2016

Upvotes: 4

Zach Dennis
Zach Dennis

Reputation: 1784

Since you know the month and year already you have solved half of your problem already because each month begins with the 1st.

You can use that to build an initial date and then you can call end_of_month to do the heavy lifting for you.

month = 4
year = 2016    
beginning_of_month = "#{year}-#{month}-01".to_date
end_of_month = beginning_of_month.end_of_month

Upvotes: 5

Related Questions