Given a Timestamp - How to return the nearest Unit and Metric,,, ex: 13 mins, 1 hour
given a timestamp, I could like to have a method that returns the correct unit (secs, hours, minutes) and the correct metric for that unit.
Examples, for a timestamp:
1 sec ago - Unit: SEC, Metric: 1
20 secs ago - Unit: SECS, Metric: 20
1 hour ago - Unit: HOUR, Metric: 1
3 hour ago - Unit: HOURS, Metric: 3
25 hours ago - Unit: DAY, Metric: 1
50 hours ago - Unit: DAYS, Metric: 2
For this method I only need t开发者_JAVA百科o go support, sec, hours and days. Not months. Ideas?
Most of the logic is already as a helper in Rails: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words
Something like this maybe:
def words_and_units(from_time, to_time = 0)
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
case distance_in_minutes
when 0..1
case distance_in_seconds
when 0..59 then {:metric => distance_in_seconds, :unit => 'SEC'}
else {:metric => 1, :unit => 'MIN'}
end
when 2..44 then {:metric => distance_in_minutes, :unit => 'MIN'}
when 45..89 then {:metric => 1, :unit => 'HOUR'}
when 90..1439 then {:metric => (distance_in_minutes.to_f / 60.0).round, :unit => 'HOUR'}
when 1440..2529 then {:metric => 1, :unit => 'DAY'}
when 2530..43199 then {:metric => (distance_in_minutes.to_f / 1440.0).round, :unit => 'DAY'}
else
raise WayToLongError
end
end
精彩评论