简体   繁体   中英

Ruby, Rails and difference between two dates

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 > 

What?!?

.created_at returns an ActiveSupport::TimeWithZone object. Try

DateTime.now - User.first.created_at.to_datetime

You can instead use

Time.now - User.first.created_at

This will report the number of seconds between now and your first user creation time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM