我正在使用Ruby和Ruby on Rails 4。
我想知道接下来两个月的每个月的第15天和最后一天的日期。
start_date = Time.now
mid_month = start_date.15th.day.of.month
last_day_of_month = start.last.day.of.month
使用Ruby或Rails实现此目的的最简单方法是什么?
答案 0 :(得分:9)
我不确定这是否适用于Rails 4:
start_date = Date.today
# => Wed, 06 Nov 2013
mid_month = (start_date + 1.month).beginning_of_month + 14
# => Sun, 15 Dec 2013
end_month = (start_date + 1.month).end_of_month
# => Tue, 31 Dec 2013
答案 1 :(得分:2)
我认为你正在寻找以下内容:
require 'date'
d = Date.today
start_date = d-d.mday
p date_15 = start_date.next_day(15)
# => #<Date: 2013-11-15 ((2456612j,0s,0n),+0s,2299161j)>
p date_last = d.next_month - d.mday
# => #<Date: 2013-11-30 ((2456627j,0s,0n),+0s,2299161j)>
答案 2 :(得分:1)
对于NEXT两个月:
start_date = Date.today
[1..2].each do |month_add|
mid_month = (start_date + month_add.month).beginning_of_month + 14
end_month = (start_date + month_add.month).end_of_month
puts 'Month: #{month_add}'
puts "Mid Month "+mid_month
puts "End Month "+end_month
end
答案 3 :(得分:1)
还有一些:
start_date == Date.today beginning = start_date.beginning_of_month middle = beginning.advance(weeks:2) end = start_date.end_of_month
看起来更具人性化。
所有这些方法都可以从ActiveSupport类扩展中获得,因此如果不使用Rails
,则必须包含它答案 4 :(得分:0)
可能有一些更简单的方法,但我想到了这一点:
require 'Date'
start_date = Date.today
mid_month = Date.new(start_date.year, start_date.month, 15)
end_of_month = Date.new(start_date.year, start_date.month+1, 1)-1
#or
end_of_month = Date.new(start_date.year, start_date.month, 1).next_month.prev_day