0

当减去两次时,返回一个浮点数:

result = Time.now - user.last_logged_in #float

对于IMAPformat_date方法,我需要一个时间对象,而不是浮点数。这可能吗?

4

1 回答 1

0

从另一个日期中减去一个日期并期望返回的值是一个日期,这没有多大意义:如果您从今天减去 Januar, 1st 2013,您希望得到什么结果?您认为您期望的 Time 对象的年份是什么?

我猜你想知道两个时间对象之间的增量。这个增量可以小(秒)或大(年)。因此 Ruby 返回两个日期之间的秒数。您可以将结果转换为更具可读性的内容。

也许你想看看distance_of_time_in_wordsRails 中的实现方式(Rails 2.3.14 的旧版本,新版本更冗长):

# File actionpack/lib/action_view/helpers/date_helper.rb, line 63
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
  from_time = from_time.to_time if from_time.respond_to?(:to_time)
  to_time = to_time.to_time if to_time.respond_to?(:to_time)
  distance_in_minutes = (((to_time - from_time).abs)/60).round
  distance_in_seconds = ((to_time - from_time).abs).round

  I18n.with_options :locale => options[:locale], :scope => :'datetime.distance_in_words' do |locale|
    case distance_in_minutes
      when 0..1
        return distance_in_minutes == 0 ?
               locale.t(:less_than_x_minutes, :count => 1) :
               locale.t(:x_minutes, :count => distance_in_minutes) unless include_seconds

        case distance_in_seconds
          when 0..4   then locale.t :less_than_x_seconds, :count => 5
          when 5..9   then locale.t :less_than_x_seconds, :count => 10
          when 10..19 then locale.t :less_than_x_seconds, :count => 20
          when 20..39 then locale.t :half_a_minute
          when 40..59 then locale.t :less_than_x_minutes, :count => 1
          else             locale.t :x_minutes,           :count => 1
        end

      when 2..44           then locale.t :x_minutes,      :count => distance_in_minutes
      when 45..89          then locale.t :about_x_hours,  :count => 1
      when 90..1439        then locale.t :about_x_hours,  :count => (distance_in_minutes.to_f / 60.0).round
      when 1440..2529      then locale.t :x_days,         :count => 1
      when 2530..43199     then locale.t :x_days,         :count => (distance_in_minutes.to_f / 1440.0).round
      when 43200..86399    then locale.t :about_x_months, :count => 1
      when 86400..525599   then locale.t :x_months,       :count => (distance_in_minutes.to_f / 43200.0).round
      else
        distance_in_years           = distance_in_minutes / 525600
        minute_offset_for_leap_year = (distance_in_years / 4) * 1440
        remainder                   = ((distance_in_minutes - minute_offset_for_leap_year) % 525600)
        if remainder < 131400
          locale.t(:about_x_years,  :count => distance_in_years)
        elsif remainder < 394200
          locale.t(:over_x_years,   :count => distance_in_years)
        else
          locale.t(:almost_x_years, :count => distance_in_years + 1)
        end
    end
  end
end
于 2013-11-11T15:28:51.837 回答