【问题标题】:Rails 3/Ruby 1.9.2 Date.tomorrow not correctRails 3/Ruby 1.9.2 Date.tomorrow 不正确
【发布时间】:2011-09-26 00:24:24
【问题描述】:

在 Mac Snow leopard 上使用 Ruby 1.9.2 和 Rail 3

ruby-1.9.2-p290 :001 > Date.today
 => Sun, 25 Sep 2011 
ruby-1.9.2-p290 :002 > Date.tomorrow
 => Tue, 27 Sep 2011 

ruby 日期类可能有问题还是与我安装 ruby​​ 的方式有关?

编辑:

ruby-1.9.2-p290 :039 > Date.current
 => Mon, 26 Sep 2011 
ruby-1.9.2-p290 :040 > DateTime.now
 => Sun, 25 Sep 2011 20:47:01 -0500

好的,所以 rails Date 类似乎有点问题。 DateTime 类似乎工作正常。感谢 derp 和 Adam

【问题讨论】:

  • 我想自己尝试一下,但我没有tomorrow 方法,这意味着一个来自rails,在你的情况下可能today 来自ruby,但tomorrow 来自rails 和那里可能是每个时区考虑的差异。试试Date.current 看看是否适用于Date.tomorrow
  • 这就是问题所在。 Date.current 返回 2011 年 9 月 26 日星期一。这解决了一个问题,但又引发了另一个问题。
  • Date.tomorrow - 总是一天之后

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

在网上查找信息时发现了这个:
https://rails.lighthouseapp.com/projects/8994/tickets/6410-dateyesterday-datetoday


查看最后一条评论:

我同意你的观点,你需要使用它有点令人困惑 Date.current 与 Date.yesterday 而不是 Date.today,但是 一般的经验法则是 Rails 不会改变 Ruby 方法的工作方式, Date.today 是哪个。我们所能做的就是添加更好的文档和 确保人们意识到细微的差别。


换句话说,使用current(rails) 而不是today(ruby) 可以避免出现问题。

【讨论】:

  • 我在伦敦时区的 BST(使用 Ruby 2.0.0)。今天在 16-04-2014 0000 和 0059 之间,Date.current 返回“2014-04-15”,而 Date.today 返回“2014-04-16”。非常令人困惑,这意味着我对“此对象是否已过期”的单元测试每天失败 1 小时!这是可怕的、意想不到的、奇怪的行为:)
【解决方案2】:

我也在观察这个。你可以试试DateTime.now.tomorrow.to_date

【讨论】:

  • 你可以做Date.today.tomorrowDate.today.yestarday
  • Date.current 使用时区,就像 Date.tomorrow 一样,而 Date.today 没有。不幸的是,这意味着 Date.today 可以等于 Date.tomorrow 或 Date.yesterday,具体取决于时区。
【解决方案3】:

你也可以Date.today + 1.day

【讨论】:

    【解决方案4】:

    如果您使用的是较新版本的 ruby​​,那么您可以使用 Date.current.tomorrow 打印明天的日期。

    例如:puts "Tomorrow's date is : #{Date.current.tomorrow}"

    要了解有关数据和时间的更多信息,请点击以下链接。

    RubyOnRails.orgRailsGithub

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 2011-07-03
      • 1970-01-01
      • 2011-06-22
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      相关资源
      最近更新 更多