Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 306
Gareth Burrows Avatar asked Dec 07 '25 07:12

Gareth Burrows


2 Answers

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
like image 147
Zach Dennis Avatar answered Dec 09 '25 21:12

Zach Dennis


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
like image 29
Matouš Borák Avatar answered Dec 09 '25 22:12

Matouš Borák