ruby/rails 中的日期范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10171111/
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 03:13:20  来源:igfitidea点击:

Date range in ruby/rails

ruby-on-railsruby

提问by Paul Brit

I want to get date range between from and till in Rails seed.

我想在 Rails 种子中获取从和到之间的日期范围。

When I try to generate date range ((Date.today - 10)..Date.today) exception occurred.

当我尝试生成日期范围 ((Date.today - 10)..Date.today) 时发生异常。

Exception message: bad value for range

异常消息:范围值错误

But in the Rails Console everything all right.

但是在 Rails 控制台中一切正常。

I think ActiveSupport are reasonable for that (my debugger told me that).

我认为 ActiveSupport 对此是合理的(我的调试器告诉我的)。

Ralls 3.1.3

拉尔斯 3.1.3

What's going on?

这是怎么回事?

回答by ecoologic

You can understand what's going on by splitting the two edges and check their class like so:

您可以通过拆分两条边并检查它们的类来了解发生了什么,如下所示:

Date.today.class #  => Date 
(Date.today - 10).class # => Date 
((Date.today - 10)..Date.today).each {|d| puts d.class} # => 10 Date works for me

The error you're experiencing is something like this:

您遇到的错误是这样的:

('a'..10) # => ArgumentError: bad value for range

Can you post the classes of your 2 edges of the range?

您可以发布范围的 2 个边缘的类吗?

(Date.today - 10).class => ?
Date.today.class       => ?

Have you overwritten any class in your rails environment? Does it work in irb?

您是否覆盖了 Rails 环境中的任何类?它在工作irb吗?

PS: As you're in rails you can use 10.days.agobut you'll need to use to_dateas it's a ActiveSupport::TimeWithZone

PS:当你在 Rails 中时,你可以使用,10.days.ago但你需要使用to_date它,因为它是一个ActiveSupport::TimeWithZone

回答by Joshua Cheek

begin
  ((Date.today - 10)..Date.today).each { |date| puts date }
rescue
  $! # => #<NameError: uninitialized constant Date>
end

require 'date'
((Date.today - 10)..Date.today).each { |date| puts date }
# >> 2012-04-06
# >> 2012-04-07
# >> 2012-04-08
# >> 2012-04-09
# >> 2012-04-10
# >> 2012-04-11
# >> 2012-04-12
# >> 2012-04-13
# >> 2012-04-14
# >> 2012-04-15
# >> 2012-04-16

回答by zolter

Everything work fine for me I am also use rails 3.1.3, my version of ruby is 1.9.2p290, maybe you need update your ruby version?

对我来说一切正常我也使用 rails 3.1.3,我的 ruby​​ 版本是 1.9.2p290,也许你需要更新你的 ruby​​ 版本?