Gareth Burrows Gareth Burrows - 5 months ago 14
Ruby Question

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 :)

Answer

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