Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby date argument out of range

Tags:

ruby

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.

like image 455
sebastyuiop Avatar asked Sep 01 '09 09:09

sebastyuiop


1 Answers

You should use the DateTime class instead of Time. (You might have to require 'date' and install the activesupport gem first.)

It is much more versatile than Time and does just what you want with DateTime.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.day and get what you want with more understandable code.

like image 190
mrueg Avatar answered Oct 13 '22 22:10

mrueg