新手问题 时间的遍历如何写?

QueXuQ · 2014年05月20日 · 最后由 QueXuQ 回复于 2014年08月05日 · 3181 次阅读

例如:2013-10-9 至 2014-5-20

我想要遍历出一组数组:

按日期算:
[2013-10-9, 2013-10-10,..., 2014-5-19, 2014-5-20]

按月份算:
[2013-10, 2013-11, ..., 2014-4, 2014-5]

按年份算:
[2013, 2014]

不知道有没有像数字1..20这样方便的方法呢?

require 'active_support/core_ext'

class Day < Date
  alias :succ :tomorrow
end

class Month < Date
  alias :succ :next_month
end

class Year < Date
  alias :succ :next_year
end

require 'date'

day1 = Date.new(2013, 10, 9)
day2 = Date.new(2014, 5, 20)

(day1..day2).each do |i| 
# do something
end

#1 楼 @lululau 这个应该怎么使用?貌似就是今天的 tomorrow?

#2 楼 @piecehealth 这个实现了天的,不知道月的怎么弄呢?

5 楼 已删除

如果你要的是字符串数据,那下面这个可以满足你的需求。异常这些需要自己处理

def get_arr_between(from, to, target='d')
  from = Date.parse(from) if from.is_a?(String)
  to = Date.parse(to) if to.is_a?(String)

  format = case target
    when 'd'    then '%Y-%m-%d'
    when 'm'  then '%Y-%m'
    when 'y'   then '%Y'
  end

  from.step(to).collect { |d| d.strftime(format) }.compact.uniq
end

献丑。

具体用法很简单

get_arr_between(from, to)
get_arr_between(from, to, 'm')
get_arr_between(from, to, 'y')

#4 楼 @QueXuQ 你看 Date 的方法啊,有 next_month, next_year,而且遍历天的时候顺便年月不都遍历了么。

月份的可能取决于你怎么用它,是字符,数字还是 date

都是挺不错的方法。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号