On Wed, 6 Sep 2006, Brad Tilley wrote:

> Say I have two time objects represented as floats like so:
>
> x = 64299600.0
> y = 1157489583.2798
>
> I want to subtract x from y and then represent the difference as years,
> months, days, hours, minutes and seconds.
>
> I don't see how the Time library would do this. Has anyone done
> something like this? If so, how?
>
> Thanks,
> Brad



harp:~ > cat a.rb
class Time
   module Units
     def __less__() "/" end
     def __more__() "*" end
     def microseconds() self.send(Float(__more__,(10 ** -6))) end
     def milliseconds() self.send(Float(__more__,(10 ** -3))) end
     def seconds() self end
     def minutes() seconds.send(__more__,60) end
     def hours() minutes.send(__more__,60) end
     def days() hours.send(__more__,24) end
     def weeks() days.send(__more__,7) end
     def months() weeks.send(__more__,4) end
     def years() months.send(__more__,12) end
     def decades() years.send(__more__,10) end
     def centuries() decades.send(__more__,10) end
     instance_methods.select{|m| m !~ /__/}.each do |plural|
       singular = plural.chop
       alias_method singular, plural
     end
   end
   module DiffUnits
     include ::Time::Units
     def __less__() "*" end
     def __more__() "/" end
   end
   alias_method "__delta__", "-" unless respond_to? "__delta__"
   def - other
     ret = __delta__ other
     ret.extend DiffUnits
     ret
   end
end
class Numeric
   include ::Time::Units
end

if $0 == __FILE__
   require "yaml"
   require "time"

   now = Time::now

   a = now
   y 'a' => a

   b = now + 2.hours + 2.minutes
   y 'b' => b

   d = b - a
   %w( seconds minutes hours days ).each do |unit|
     y "d.#{ unit }" => d.send(unit)
   end
end


harp:~ > ruby a.rb
a: 2006-09-05 15:26:06.341147 -06:00
b: 2006-09-05 17:28:06.341147 -06:00
d.seconds: 7320.0
d.minutes: 122.0
d.hours: 2.03333333333333
d.days: 0.0847222222222222



regards.


-a
-- 
what science finds to be nonexistent, we must accept as nonexistent; but what
science merely does not find is a completely different matter... it is quite
clear that there are many, many mysterious things.
- h.h. the 14th dalai lama