I’m trying to make a time with Time.local which in my code is dynamic. On the first of each month the values I’m passing are Time.local(2009, 9, -1, 0). In PHP this would set the time to the last day of the previous month. In ruby I just get “ArgumentError: argument out of range”.
Am I using the wrong method or something? Thanks.
You should use the
DateTimeclass instead ofTime. (You might have torequire 'date'and install theactivesupportgem first.)It is much more versatile than
Timeand does just what you want withDateTime.civil(2009,9 - 1,-1,0).Passing -1 for the day gives you the date of the last day of the month from the second argument, so you have to subtract 1 from the current month.
If you are in Rails, you could just do
DateTime.civil(2009,9,1,0) - 1.dayand get what you want with more understandable code.