有没有办法在接下来的6个月里找到所有星期三的日期

时间:2014-05-20 09:11:06

标签: ruby-on-rails ruby ruby-on-rails-3

我有用例,如果用户选择日期,如2014年5月21日(即星期三)。然后,我需要找到接下来6个月的所有星期三的日期。

在rails中有没有更简单的方法或api?

2 个答案:

答案 0 :(得分:3)

有点奇怪的任务。但为什么不呢?

2.1.1 :041 > date = Date.today + 1.day
Wed, 21 May 2014
2.1.1 :042 > array = []
[]
2.1.1 :043 > 24.times { array.push(date); date += 7.days; }
24
2.1.1 :044 > array
[
    [ 0] Wed, 21 May 2014,
    [ 1] Wed, 28 May 2014,
    [ 2] Wed, 04 Jun 2014,
    [ 3] Wed, 11 Jun 2014,
    [ 4] Wed, 18 Jun 2014,
    [ 5] Wed, 25 Jun 2014,
    [ 6] Wed, 02 Jul 2014,
    [ 7] Wed, 09 Jul 2014,
    [ 8] Wed, 16 Jul 2014,
    [ 9] Wed, 23 Jul 2014,
    [10] Wed, 30 Jul 2014,
    [11] Wed, 06 Aug 2014,
    [12] Wed, 13 Aug 2014,
    [13] Wed, 20 Aug 2014,
    [14] Wed, 27 Aug 2014,
    [15] Wed, 03 Sep 2014,
    [16] Wed, 10 Sep 2014,
    [17] Wed, 17 Sep 2014,
    [18] Wed, 24 Sep 2014,
    [19] Wed, 01 Oct 2014,
    [20] Wed, 08 Oct 2014,
    [21] Wed, 15 Oct 2014,
    [22] Wed, 22 Oct 2014,
    [23] Wed, 29 Oct 2014
]

答案 1 :(得分:1)

require 'date'

today = Date.today
six_months = today.next_month(6)
(today..six_months).select {|date| date.wday == today.wday}

或者如果你真的想要所有星期三:

(today..six_months).select &:wednesday?