From: Ken Bloom Date: 2006-09-06T12:25:06+09:00 Subject: Re: representing a span of time On Tue, 05 Sep 2006 15:26:41 -0600, ara.t.howard wrote: > 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? > [SNIP-CODE] > > 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 I think he wants something more like this, where all of the different options collectively add up to the total time interval (rather than yours where each different unit of time nonetheless represents the whole span) class TimeSpan # takes input in seconds because that's what Time#to_i returns def initialize(seconds) @raw_seconds=seconds breakdown end attr_reader :seconds,:minutes,:hours,:days attr_reader :raw_seconds private attr_writer :seconds,:minutes,:hours,:days # [:x=,y] represents that y is the maximum number of x before # carrying over to the next larger unit of time FACTORS=[[:seconds=,60],[:minutes=,60], [:hours=,24],[:days=,nil]] def breakdown higherintervals=@raw_seconds FACTORS.each do |method, max| higherintervals, thisinterval= \ higherintervals.divmod(max) unless max==nil thisinterval=higherintervals if max==nil send(method,thisinterval) end end end irb(main):020:0> a=Time.now.to_i => 1157512271 irb(main):021:0> b=Time.now.to_i => 1157512296 irb(main):025:0> TimeSpan.new(b-a) => # Can't do years and months without more complicated math, and a definite knowledge of what the start date and end date are. But at least this should be closer. --Ken Bloom -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/