给定一个Ruby日期,是否存在用于计算该日期的下一个周年纪念日的one liner?
例如,如果日期是2011年5月1日,则下一个周年纪念将是2012年5月1日,但是如果日期是2011年12月1日,则下一个周年纪念日将是2011年12月1日(因为该日期尚未到达)。
发布于 2011-06-08 01:56:38
有一个很好的方法可以做到这一点,称为递归。您可以签出源代码或一些示例:
例如,如果您有一个date集,您可以尝试:
date = ...
recurrence = Recurrence.new(every: :year, on: [date.month, date.day])
puts recurrence.next发布于 2011-06-05 04:03:56
如果您的date变量是Date的实例,则可以使用>>
返回一个比当前日期晚n个月的新日期对象。
所以你可以这样做:
one_year_later = date >> 12同样的方法也适用于DateTime。如果您只有一个字符串,那么您可以使用parse方法:
next_year = Date.parse('May 01, 2011') >> 12
next_year_string = (Date.parse('May 01, 2011') >> 12).to_s我建议你尽可能多地使用日期库(Date和DateTime),但如果你知道Rails会一直存在,或者你不介意根据需要手动引入active_support,你可以使用Rails扩展(比如1.year)。
发布于 2011-06-05 04:02:56
你可以使用Ruby的Date类来实现:
the_date = Date.parse('jan 1, 2011')
(the_date < Date.today) ? the_date + 365 : the_date # => Sun, 01 Jan 2012
the_date = Date.parse('dec 31, 2011')
(the_date < Date.today) ? the_date.next_year : the_date # => Sat, 31 Dec 2011或者,为了方便起见,使用ActiveSupport的Date class extensions
require 'active_support/core_ext/date/calculations'
the_date = Date.parse('jan 1, 2011')
(the_date < Date.today) ? the_date.next_year : the_date # => Sun, 01 Jan 2012
the_date = Date.parse('dec 31, 2011')
(the_date < Date.today) ? the_date.next_year : the_date # => Sat, 31 Dec 2011https://stackoverflow.com/questions/6238972
复制相似问题