2

我正在使用 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 最简单的方法是什么?

4

5 回答 5

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
于 2013-11-06T13:13:56.393 回答
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)>
于 2013-11-06T13:17:09.627 回答
1

接下来的两个月:

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
于 2013-11-06T13:27:08.803 回答
1

这里还有一些:

    start_date == Date.today

    开始 = start_date.beginning_of_month
    中间=开始。提前(周:2)
    结束 = start_date.end_of_month

看起来更具人类可读性。

所有这些方法都可以从 ActiveSupport 类扩展中获得,所以如果不使用 Rails,你必须包含它

于 2013-11-06T14:59:40.663 回答
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
于 2013-11-06T13:09:30.500 回答