【发布时间】:2011-08-30 19:12:42
【问题描述】:
我想计算从特定开始和结束时间开始的持续时间,并以小时/分钟/秒为单位输出,以及该持续时间与整个月相比的百分比。
有时,一个月内的总持续时间包含多个持续时间块。这是一个例子:
用 Ruby 思考负载:
Start = Date.new(2011-09-01 00:00:00) #24h clock - start of month
End = Date.new(2011-09-31 24:00:00) # end of month
Duration1 = Date.new(2011-09-03 12:30:00) Date.new(2011-09-11 12:30:00) #From - to
Duration2 = Date.new(2011-09-13 12:30:00) Date.new(2011-09-18 12:30:00) #From - to
Duration = Duration 1 + Duration2 #Might be even more durations during a month
Puts Duration.to_s
Total = Start + End
Percentage = (Duration / Total) * 100
知道如何从上面的代码中创建一个方法吗?如果我能运行类似或更简单的东西,那就太棒了:
Duration1 = Timedifference "2011-09-03 12:30:00", "2011-09-11 12:30:00" # Specify duration like this
Duration2 = Timedifference "2011-09-13 12:30:00", "2011-09-18 12:30:00" # Specify duration like this
Duration = Duration1 + Duration2
puts Duration
puts Percentage.Duration
提前感谢您的帮助。
【问题讨论】:
-
对你来说“整月”是什么?这可能从 28 天到 31 天不等。还是您的所有日期都在一个月内,而整个月都是实际日期?
-
包含持续时间的月份。一个持续时间可能跨越几个月,但为了简化解决方案,最简单的方法是打破几个月之间的持续时间。