Ruby、Rails 和两个日期之间的差异 [英] Ruby, Rails and difference between two dates

查看:40
本文介绍了Ruby、Rails 和两个日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会让这个例子不言自明:

I will let the example speak for it self:

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 > 

什么?!?

推荐答案

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

.created_at returns an ActiveSupport::TimeWithZone object. Try

DateTime.now - User.first.created_at.to_datetime

这篇关于Ruby、Rails 和两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆