Вывод в часах / минутах / секундах довольно прост:
Time.at(duration).gmtime.strftime("%R:%S")
Подробности см. http://www.ruby -forum.com / topic / 48877
Дляв процентах мне понадобится более подробная спецификация.
- Какова база вашего месяца?В феврале 28 дней (но не забывайте о високосных годах), в других месяцах - 30 или 31 день.
- Могут ли ваши продолжительности быть разными в разные месяцы?
- Не могли бы вы дать некоторые данные испытаний и ожидаемый результат?
Ниже одно решение с некоторыми допущениями.
require 'date'
=begin rdoc
Calculate seconds for a given month
=end
def seconds_of_month( year, month )
raise ArgumentError if month > 12
month_start = DateTime.new(year, month, 1, 0) #24h clock , start of month
if month == 12
month_end = DateTime.new(year + 1, 1, 1, 0) # jan 1st of following year
else
month_end = DateTime.new(year, month+1, 1) # start of next month
end
days = month_end - month_start
#~ puts "%i-%i has %i days (%s-%s)" % [year, month, days, month_start, month_end ]
days * 24 * 60 * 60 #convert month in second --- no check for leap seconds
end
=begin rdoc
Calculate percentage of duration in seconds per month.
=end
def percentage_of_month( duration, year, month )
(duration / seconds_of_month(year,month)) * 100
end
duration = #=> 1123200s
( Time.local(2011, 9, 11, 12, 30, 00) - Time.local(2011, 9, 03, 12, 30, 00) ) +
( Time.local(2011, 9, 18, 12, 30, 00) - Time.local(2011, 9, 13, 12, 30, 00) )
1.upto(12){|mon|
puts '%is is %.2f%% of 2011/%i (%is)' % [ duration, percentage_of_month( duration, 2011,mon), mon, seconds_of_month( 2011, mon ) ]
}
Результат:
1123200s is 41.94% of 2011/1 (2678400s)
1123200s is 46.43% of 2011/2 (2419200s)
1123200s is 41.94% of 2011/3 (2678400s)
1123200s is 43.33% of 2011/4 (2592000s)
1123200s is 41.94% of 2011/5 (2678400s)
1123200s is 43.33% of 2011/6 (2592000s)
1123200s is 41.94% of 2011/7 (2678400s)
1123200s is 41.94% of 2011/8 (2678400s)
1123200s is 43.33% of 2011/9 (2592000s)
1123200s is 41.94% of 2011/10 (2678400s)
1123200s is 43.33% of 2011/11 (2592000s)
1123200s is 41.94% of 2011/12 (2678400s)