tags:

views:

211

answers:

2

How would I, for example, find out that 6pm is 50% between 4pm and 8pm?
Or that 12am Wednesday is 50% between 12pm Tuesday and 12pm Wednesday?

+5  A: 

Convert the times to seconds, calculate the span in seconds, calculate the difference between your desired time and the first time in seconds, calculate the fraction of the whole span, and then multiply by 100%?

Example:

12 AM = 0 seconds (of day)

12 PM = 43200 seconds (of day)

Your desired time = 3 AM = 10800 seconds of day

Total time span = 43200 - 0 = 43200 seconds

Time difference of your desired time from first time = 10800 - 0 = 10800 seconds

Fraction = 10800 / 43200 = 0.25

Percentage = 0.25 * 100% = 25%

(Sorry don't know Ruby but there's the idea.)

John at CashCommons
I'm sorry, I'm a bit confused. Can you turn that into a mathematical equation?
c00lryguy
Actually, you can just subtract Time object from each other, so you use the exact same code as you would to compute the ratio of numbers. Dynamic languages ftw!
Adrian
`(a-b)/(a-c)*100` ???
Adrian
Adrian: What would a, b, and c be?
c00lryguy
Correct algorithm would be (c-a) / (b-a) * 100where c is the middle time (10800), b is the end time and a is the start time.
Ryan Bigg
+4  A: 
require 'date'

start = Date.new(2008, 4, 10)
middle = Date.new(2009, 12, 12)
enddate = Date.new(2009, 4, 10)

duration = start - enddate #Duration of the whole time
desired  = middle - start #Difference between desired + Start
fraction = desired / duration
percentage = fraction * 100

puts percentage.to_i

Thanks to 'John W' for the math.

CodeJoust
Ah, there's the rub ... y ;)
John at CashCommons
Simplified: (middle-start)/(end-start)*100
Ryan Bigg
True, but this shows the use of date, rational numbers, and its a little clearer.
CodeJoust