Ruby:在上个月重复了几天

时间:2015-05-20 10:16:38

标签: ruby date

我需要能够循环上个月的所有日子,并在解析的日子里做点什么。这就是我到目前为止所做的:

to_date

我的问题是我似乎无法让{{1}}等于上个月的最后一天。我已经阅读了很多类似的问题,但大多数问题似乎都更倾向于Rails,在这种情况下这对我没有帮助。

4 个答案:

答案 0 :(得分:6)

require 'date'

d = Date.today << 1 # << 1 is one month earlier
(Date.new(d.year, d.month, 1)..Date.new(d.year, d.month,-1)).each{|date| p date}

答案 1 :(得分:2)

您还可以使用...排除结束值。

例如:

(1..5).to_a
=> [1, 2, 3, 4, 5]
(1...5).to_a
=> [1, 2, 3, 4]

所以你可以这样写:

if d.month != 1
   from_date = Date.new(d.year, d.month - 1, 1)
else
   from_date = Date.new(d.year-1, -1)
end
to_date = Date.new(d.year, d.month)

(from_date...to_date).map { |day| puts day}

输出:

2015-04-01
2015-04-02
2015-04-03
......
2015-04-29
2015-04-30

答案 2 :(得分:1)

我会这样做:

require 'date'

d = Date.today << 1
start = Date.new(d.year, d.month)
(start...(start >> 1)).each { |d| p d }
  #-> #<Date: 2015-04-01 ((2457114j,0s,0n),+0s,2299161j)>
  #   #<Date: 2015-04-02 ((2457115j,0s,0n),+0s,2299161j)>
  #   ...
  #   #<Date: 2015-04-30 ((2457143j,0s,0n),+0s,2299161j)>

答案 3 :(得分:0)

也可以使用prev_day函数:

require 'date'

d = Date.today

from_date = Date.new(d.year, d.month - 1, 1)
to_date = Date.new(d.year, d.month, 1).prev_day

from_date..to_date.each do |day|
    #Do stuff with day
end