给定日期,如何有效地计算给定顺序的下一个日期(每周,每月,每年)? [英] Given a date, how can I efficiently calculate the next date in a given sequence (weekly, monthly, annually)?

查看:152
本文介绍了给定日期,如何有效地计算给定顺序的下一个日期(每周,每月,每年)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有各种日期序列,如每周,每月和每年。给定过去的任意日期,我需要按顺序计算下一个未来日期。

In my application I have a variety of date sequences, such as Weekly, Monthly and Annually. Given an arbitrary date in the past, I need to calculate the next future date in the sequence.

目前我正在使用次优循环。这是一个简化的例子(在Ruby / Rails中):

At the moment I'm using a sub-optimal loop. Here's a simplified example (in Ruby/Rails):

def calculate_next_date(from_date)
  next_date = from_date
  while next_date < Date.today
    next_date += 1.week # (or 1.month)
  end
  next_date
end

而不是执行一个循环(尽管简单,效率低下,特别是在远处的日期时),我想用日期算术来计算两个日期之间的周数(或月,年),计算余数,并使用这些值生成下一个日期。

Rather than perform a loop (which, although simple, is inefficient especially when given a date in the distant past) I'd like to do this with date arithmetic by calculating the number of weeks (or months, years) between the two dates, calculating the remainder and using these values to generate the next date.

这是正确的方法,还是我缺少一个特别聪明的Ruby解决方法?或者我应该简单地坚持我的循环吗?

Is this the right approach, or am I missing a particularly clever 'Ruby' way of solving this? Or should I just stick with my loop for the simplicity of it all?

推荐答案

由于您将此问题标记为 ruby​​-on-rails 我想你使用的是Rails。
ActiveSupport引入了计算模块,它提供了一个有用的 #change 方法。

Because you tagged this question as ruby-on-rails, I suppose you are using Rails. ActiveSupport introduces the calculation module which provides an helpful #change method.

date = Date.today
date.advance(:weeks => 1)
date.change(:days => 7)
# => next week

这篇关于给定日期,如何有效地计算给定顺序的下一个日期(每周,每月,每年)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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