【问题标题】:Ruby, Rails and difference between two datesRuby,Rails和两个日期之间的差异
【发布时间】:2011-06-27 03:22:21
【问题描述】:

我会让例子自己说话:

ruby-1.9.2-p0 >   DateTime.now
 => Mon, 14 Feb 2011 20:02:49 +0100 
ruby-1.9.2-p0 > User.first.created_at
 => Tue, 04 May 2010 07:03:24 CEST +02:00 
ruby-1.9.2-p0 > DateTime.now-User.first.created_at
TypeError: expected numeric or date
    from /Users/Jacob/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/date.rb:1356:in `-'
    from /Users/Jacob/.rvm/gems/ruby-1.9.2-p0@loyaltric_template/gems/activesupport-3.0.3/lib/active_support/core_ext/date/calculations.rb:98:in `minus_with_duration'
    from (irb):47
    from /Users/Jacob/.rvm/gems/ruby-1.9.2-p0@loyaltric_template/gems/railties-3.0.3/lib/rails/commands/console.rb:44:in `start'
    from /Users/Jacob/.rvm/gems/ruby-1.9.2-p0@loyaltric_template/gems/railties-3.0.3/lib/rails/commands/console.rb:8:in `start'
    from /Users/Jacob/.rvm/gems/ruby-1.9.2-p0@loyaltric_template/gems/railties-3.0.3/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
ruby-1.9.2-p0 > 

什么?!?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    .created_at 返回一个 ActiveSupport::TimeWithZone 对象。试试

    DateTime.now - User.first.created_at.to_datetime
    

    【讨论】:

      【解决方案2】:

      你可以改用

      Time.now - User.first.created_at
      

      这将报告从现在到您的第一个用户创建时间之间的秒数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-24
        • 2011-10-29
        • 1970-01-01
        • 2015-02-23
        • 2014-02-12
        • 2015-09-14
        • 2015-06-21
        • 2020-02-06
        相关资源
        最近更新 更多