Getting number of days in a month

In PHP, there was an argument you could pass to the Date function to
get the number of days in the current month:

echo date(“t”); // Outputs “28” for February

I don’t see anything like this in Ruby/Rails. Right now, I’m using a
very ugly line to pull the last day of the month:

@number_of_days = (Date.strptime(Date.today.strftime("%Y-%m-01")) >>

    • 1

Basically, it takes the first day of the current month, adds one
month, and then subtracts one day. Am I completely overlooking some
obvious and easy way to do this? (I’m assuming so).

Hey,
This should work.

@number_of_days = Date.civil(year, month, -1).day

Cheers,
Eric G.

Dylan M. wrote:

Basically, it takes the first day of the current month, adds one
month, and then subtracts one day. Am I completely overlooking some
obvious and easy way to do this? (I’m assuming so).


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails


Eric G.
http://www.ericgoodwin.com

$ ./script/console
Loading development environment.

Time.days_in_month 2
=> 28

Time.days_in_month 2, 2008
=> 29

Kent

oops …

today = Date.today
@number_of_days = Date.civil(today.year, today.month, -1).day

Eric G. wrote:

In PHP, there was an argument you could pass to the Date function to
Basically, it takes the first day of the current month, adds one
month, and then subtracts one day. Am I completely overlooking some
obvious and easy way to do this? (I’m assuming so).


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails


Eric G.
http://www.ericgoodwin.com

How about using:

Time.days_in_month(month, year=nil)

Bob S.
http://www.railtie.net/

Beautiful! Thank you everyone!