每个月用日期对象迭代 [英] Iterate every month with date objects

查看:116
本文介绍了每个月用日期对象迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个ruby Date对象,我想每个月迭代一次。例如,如果我有Date.new(2008年12月)和Date.new(2009,3),那么将会得到2008-12,2009-1,2009-2,2009-3(当然是Date对象)。我尝试使用范围,但它每天产生。我看到日期的步骤方法,但它只允许我通过天数(每个月有不同的数量)。任何人都有任何想法?

解决方案

我已经添加了以下方法到Date类:

  class Date 
def all_months_until to
from = self
from,to = to,from if from>到
m = Date.new from.year,from.month
result = []
while m <= to
result<< m
m>> = 1
结束

结果
结束
结束

您可以使用它:

 >> t = Date.today 
=> #< Date:2009-11-12(4910295 / 2,0,2299161)>
>> t.all_months_until(t + 100)
=> [#< Date:2009-11-01(4910273 / 2,0,2299161)>#< Date:2009-12-01(4910333 / 2,0,2299161)>#< Date: 2010-01-01(4910395 / 2,0,2299161)><日期:2010-02-01(4910457 / 2,0,2299161)>]

好的,所以更多的rubyish方法IMHO将是一些东西:

 code> class Month< Date 
def succ
self>> 1
end
end

 >> t = Month.today 
=> #< Month:2009-11-13(4910297 / 2,0,2299161)>
>> (t..t + 100).to_a
=> [#< Month:2009-11-13(4910297 / 2,0,2299161)>#< Month:2009-12-13(4910357 / 2,0,2299161)>#< Month: 2010-01-13(4910419 / 2,0,2299161)>#< Month:2010-02-13(4910481 / 2,0,2299161)>]

但是,您需要小心使用月的第一天(或在月份实施此类逻辑)...


So I have two ruby Date objects, and I want to iterate them every month. For example if I have Date.new(2008, 12) and Date.new(2009, 3), it would yield me 2008-12, 2009-1, 2009-2, 2009-3 (as Date objects of course). I tried using range, but it yields every day. I saw step method for Date however it only allows me to pass number of days (and each month has different number of those). Anyone have any ideas?

解决方案

I have added following method to Date class:

class Date
  def all_months_until to
    from = self
    from, to = to, from if from > to
    m = Date.new from.year, from.month
    result = []
    while m <= to
      result << m
      m >>= 1
    end

    result
  end
end

You use it like:

>> t = Date.today
=> #<Date: 2009-11-12 (4910295/2,0,2299161)>
>> t.all_months_until(t+100)   
=> [#<Date: 2009-11-01 (4910273/2,0,2299161)>, #<Date: 2009-12-01 (4910333/2,0,2299161)>, #<Date: 2010-01-01 (4910395/2,0,2299161)>, #<Date: 2010-02-01 (4910457/2,0,2299161)>]

Ok, so, more rubyish approach IMHO would be something along:

class Month<Date
  def succ
    self >> 1
  end
end

and

>> t = Month.today
=> #<Month: 2009-11-13 (4910297/2,0,2299161)>
>> (t..t+100).to_a
=> [#<Month: 2009-11-13 (4910297/2,0,2299161)>, #<Month: 2009-12-13 (4910357/2,0,2299161)>, #<Month: 2010-01-13 (4910419/2,0,2299161)>, #<Month: 2010-02-13 (4910481/2,0,2299161)>]

But you would need to be careful to use first days of month (or implement such logic in Month)...

这篇关于每个月用日期对象迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆