RyanScottLewis
RyanScottLewis

Reputation: 14026

Ruby: Time difference in percentage?

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?

Upvotes: 0

Views: 1988

Answers (2)

CodeJoust
CodeJoust

Reputation: 3800

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.

Upvotes: 4

John
John

Reputation: 16007

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.)

Upvotes: 6

Related Questions