How would I get the last day of a current month given the month number.
如果给出月份数,我将如何获得当月的最后一天。
For example if the month is 8 (August 2014), how would I get the last day of the month? (The last day of August is the 31th). The function(8) would return 31.
例如,如果月份是8(2014年8月),我将如何获得该月的最后一天? (8月的最后一天是31日)。函数(8)将返回31。
Thank you for the help.
感谢您的帮助。
2 个解决方案
#1
2
Using Date::civil
:
使用Date :: civil:
require 'date'
Date.civil(2014, 8, -1).day
# => 31
According to the documentation:
根据文件:
The month and the day of month should be a negative or a positive number (as a relative month/day from the end of year/month when negative). They should not be zero.
月份和月份应为负数或正数(作为从年末/月结束时的相对月/日)。它们不应该是零。
#2
1
require 'date'
def function(month)
raise "invalid month" unless month.is_a?(Integer) and month.between?(1, 12)
month == 12 ? 31 : Date.new(Date.today.year,month+1,1).prev_day.day
end
function(8)
# => 31
source: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-prev_day
来源:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-prev_day
#1
2
Using Date::civil
:
使用Date :: civil:
require 'date'
Date.civil(2014, 8, -1).day
# => 31
According to the documentation:
根据文件:
The month and the day of month should be a negative or a positive number (as a relative month/day from the end of year/month when negative). They should not be zero.
月份和月份应为负数或正数(作为从年末/月结束时的相对月/日)。它们不应该是零。
#2
1
require 'date'
def function(month)
raise "invalid month" unless month.is_a?(Integer) and month.between?(1, 12)
month == 12 ? 31 : Date.new(Date.today.year,month+1,1).prev_day.day
end
function(8)
# => 31
source: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-prev_day
来源:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-prev_day