Gareth Burrows Gareth Burrows - 8 months ago 30
Ruby Question

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

I have a table with a column for

, which is an
, and a column for
, which again is an
. I need (in ruby) to be able to end up with a
and an
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 :)


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