Is there a method of Date or Time that gives the number of days in a date's month or the last day of the month like:
d = Date.new(2005,4,20)
d.days_in_month #-> 30
#or
d.last_day_of_month #-> 30
Thanks,
Dan
Is there a method of Date or Time that gives the number of days in a date's month or the last day of the month like:
d = Date.new(2005,4,20)
d.days_in_month #-> 30
#or
d.last_day_of_month #-> 30
Thanks,
Dan
Hi --
Is there a method of Date or Time that gives the number of days in a date's month or the last day of the month like:
d = Date.new(2005,4,20)
d.days_in_month #-> 30
#or
d.last_day_of_month #-> 30
Funny you should ask
This came up on IRC a month or two ago, and the answer appears to be
no. So I wrote one:
# Date.dim -- days in month
require 'date'
class Date
def dim
d,m,y = mday,month,year
d += 1 while Date.valid_civil?(y,m,d)
d - 1
end
end
if __FILE__ == $0
puts (Date.today >> 1).dim
puts (Date.today << 1).dim
puts (Date.new(2004,2)).dim
end
__END__
David
On Tue, 26 Apr 2005, Dan Fitzpatrick wrote:
--
David A. Black
dblack@wobblini.net
class Date
def days_in_month
((Date.new(year, month, 1) >> 1)-1).day
end
end
d = Date.new(2005,4,20)
puts d.days_in_month #-> 30
from the excellent impl in the 'days of month' thread earlier this week:
harp:~ > cat a.rb
require 'date'
class Date
def days_in_month
self::class.civil(year, month, -1).day
end
alias dim days_in_month
def weekdays
(1..dim).to_a
end
end
p Date::new(2005, 02).weekdays
p Date::new(2005, 12).weekdays
harp:~ > ruby a.rb
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
harp:~ > cal 2 2005
February 2005
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28
harp:~ > cal 12 2005
December 2005
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
boy i love ruby.
cheers.
-a
On Tue, 26 Apr 2005, Dan Fitzpatrick wrote:
Is there a method of Date or Time that gives the number of days in a date's
month or the last day of the month like:d = Date.new(2005,4,20)
d.days_in_month #-> 30
#or
d.last_day_of_month #-> 30
email :: ara [dot] t [dot] howard [at] noaa [dot] gov
phone :: 303.497.6469
although gold dust is precious, when it gets in your eyes, it obstructs
your vision. --hsi-tang
===============================================================================
JC,
Thanks for the simple solution.
Dan
jc wrote:
class Date
def days_in_month
((Date.new(year, month, 1) >> 1)-1).day
end
endd = Date.new(2005,4,20) puts d.days_in_month #-> 30
!!! Yowser!
Nice! Here's a slight variation that's even simpler:
class Date
def days_in_month
Date.civil(year, month, -1).day
end
end