Ruby 查找下周四(或一周中的任何一天)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7621322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:05:02  来源:igfitidea点击:

Ruby find next Thursday (or any day of the week)

ruby-on-railsrubyruby-on-rails-3datetime

提问by neon

What is the best way to calculate the Date, Month, and Year of the next Thursday (or any day) from today in Ruby?

在 Ruby 中从今天开始计算下一个星期四(或任何一天)的日期、月份和年份的最佳方法是什么?

UPDATEIn order to create dummy objects, I'm trying to figure out how to calculate a random time. In all, I'd like to produce a random time between 5 and 10 PM on the next Thursday of the week.

更新为了创建虚拟对象,我试图弄清楚如何计算随机时间。总之,我想在一周的下一个星期四下午 5 点到 10 点之间生成一个随机时间。

回答by millimoose

date = Date.today
date += 1 + ((3-date.wday) % 7)
# date is now next Thursday

回答by Adam Eberlin

DateTime.now.next_week.next_day(3)

DateTime.now.next_week.next_day(3)

As @Nils Riedemann pointed out:

正如@Nils Riedemann 指出的那样:

Keep in mind that it will not get the next thursday, but the thursday of the next week. eg. If tomorrow was thursday, it won't return tomorrow, but next week's thursdays.

请记住,它不会是下一个星期四,而是下周的星期四。例如。如果明天是星期四,它不会在明天返回,而是在下周的星期四。

Here is an excerpt of some code I've written recently which handles the missing case.

这是我最近编写的一些处理丢失情况的代码的摘录。

require 'date'

module DateTimeMixin

  def next_week
    self + (7 - self.wday)
  end

  def next_wday (n)
    n > self.wday ? self + (n - self.wday) : self.next_week.next_day(n)
  end

end

# Example

ruby-1.9.3-p194 :001 > x = DateTime.now.extend(DateTimeMixin)
 => #<DateTime: 2012-10-19T15:46:57-05:00 ... > 

ruby-1.9.3-p194 :002 > x.next_week
 => #<DateTime: 2012-10-21T15:46:57-05:00 ... > 

ruby-1.9.3-p194 :003 > x.next_wday(4)
 => #<DateTime: 2012-10-25T15:46:57-05:00 ... > 

回答by WattsInABox

Aside from getting next Thursday as the others described, Ruby provides easy methods to get the month and year from any date:

除了像其他人描述的那样获取下周四之外,Ruby 还提供了从任何日期获取月份和年份的简单方法:

month = date.month
year = date.year

Inside of Rails you can easily get next Thursday as such:

在 Rails 内部,您可以轻松地在下周四获得这样的信息:

next_thur = Date.today.next_week.advance(:days=>3)

回答by Dave Newton

IMO the chroniclibrary is awesome for stuff like this.

IMO慢性图书馆非常适合这样的东西。

The Ruby code would be:

Ruby 代码将是:

def date_of_next(day)
    Chronic.parse('next #{day}')
end

回答by Sreenivasan AC

This SO answer is also short and simple https://stackoverflow.com/a/7930553/3766839

这个 SO 答案也很简短 https://stackoverflow.com/a/7930553/3766839

def date_of_next(day)
  date  = Date.parse(day)
  delta = date > Date.today ? 0 : 7
  date + delta
end

date_of_next "Thursday"