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

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

问题描述

在我的应用程序有很多种日期序列,如每周,每月和每年的。给定一个任意的日期已经过了,我需要计算下的的未来的日期的顺序进行。

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.

这是正确的做法,还是我失去了解决这个的一个特别聪明的'红宝石'的方式?或者我应该只是我的环路这一切的简单坚持?

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?

推荐答案

,我想你正在使用Rails。 的ActiveSupport介绍了<一href="http://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/date_time/calculations.rb">calculation模块,它提供了一个有用的 #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天全站免登陆