gpt4 book ai didi

Ruby - 将持续时间计算为整月的百分比

转载 作者:数据小太阳 更新时间:2023-10-29 08:40:38 26 4
gpt4 key购买 nike

我想计算从特定开始时间到结束时间的持续时间,并以小时/分钟/秒为单位输出,以及该持续时间与整个月相比的百分比。

有时,一个月中的总持续时间在多个持续时间 block 中。这是一个例子:

考虑用 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

预先感谢您的帮助。

最佳答案

有很多方法可以解决这个问题。假设一个人想要避免对标准库以外的任何东西的依赖,这就是我要做的:

require 'time'

# Calculate difference between two given Time objects
# and output as hours, minutes and seconds
def duration(time_start, time_end)
secs = (time_end - time_start).to_i
hours = secs / 3600;
secs -= hours * 3600
mins = secs / 60;
secs -= mins * 60
puts "#{hours}h #{mins}m #{secs}s"
end

# EDIT: Simpler and more elegant method (thanks to @knut)
def duration2(time_start, time_end)
puts Time.at(time_end - time_start).gmtime.strftime('%dd %Hh %Mm %Ss')
end

# Calculate the difference between two given Time objects,
# and the duration of the month the latter is in, then
# output the ratio as a percentage with 2 decimal places
def percentage_of_month(time_start, time_end)
time_secs = time_end - time_start
month_this = Date.civil(time_end.year, time_end.month, 1)
month_next = month_this.next_month
month_secs = (month_next - month_this) * 24 * 3600
percentage = (time_secs * 100.0 / month_secs)
puts '%2.2f%%' % percentage
end

time1a = Time.parse '2011-09-03 12:30:00'
time1b = Time.parse '2011-09-11 12:30:00'
duration time1a, time1b # => 192h 0m 0s
percentage_of_month time1a, time1b # => 26.67%

time2a = Time.parse '2011-09-13 12:30:00'
time2b = Time.parse '2011-09-18 12:30:00'
duration time2a, time2b # => 120h 0m 0s
percentage_of_month time2a, time2b # => 16.67%

time3a = Time.parse '2011-08-30 11:03:18'
time3b = Time.parse '2011-08-30 23:31:54'
duration time3a, time3b # => 12h 28m 36s
percentage_of_month time3a, time3b # => 1.68%

关于Ruby - 将持续时间计算为整月的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com