我有几秒钟.让我们说270921.我怎么能显示这个数字,说它是xx天,yy小时,zz分钟,ww秒?
Mik*_*use 150
它可以非常简洁地使用divmod:
t = 270921
mm, ss = t.divmod(60) #=> [4515, 21]
hh, mm = mm.divmod(60) #=> [75, 15]
dd, hh = hh.divmod(24) #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]
#=> 3 days, 3 hours, 15 minutes and 21 seconds
Run Code Online (Sandbox Code Playgroud)
你可以通过创造性地collect或者可能来进一步干燥它inject,但是当核心逻辑是三条线时它可能是过度的.
Kel*_*vin 13
我希望有一种比使用divmod更简单的方法,但这是我发现的最干燥和可重复使用的方式:
def seconds_to_units(seconds)
'%d days, %d hours, %d minutes, %d seconds' %
# the .reverse lets us put the larger units first for readability
[24,60,60].reverse.inject([seconds]) {|result, unitsize|
result[0,0] = result.shift.divmod(unitsize)
result
}
end
Run Code Online (Sandbox Code Playgroud)
通过更改格式字符串和第一个内联数组(即[24,60,60])可以轻松调整该方法.
增强版
class TieredUnitFormatter
# if you set this, '%d' must appear as many times as there are units
attr_accessor :format_string
def initialize(unit_names=%w(days hours minutes seconds), conversion_factors=[24, 60, 60])
@unit_names = unit_names
@factors = conversion_factors
@format_string = unit_names.map {|name| "%d #{name}" }.join(', ')
# the .reverse helps us iterate more effectively
@reversed_factors = @factors.reverse
end
# e.g. seconds
def format(smallest_unit_amount)
parts = split(smallest_unit_amount)
@format_string % parts
end
def split(smallest_unit_amount)
# go from smallest to largest unit
@reversed_factors.inject([smallest_unit_amount]) {|result, unitsize|
# Remove the most significant item (left side), convert it, then
# add the 2-element array to the left side of the result.
result[0,0] = result.shift.divmod(unitsize)
result
}
end
end
Run Code Online (Sandbox Code Playgroud)
例子:
fmt = TieredUnitFormatter.new
fmt.format(270921) # => "3 days, 3 hours, 15 minutes, 21 seconds"
fmt = TieredUnitFormatter.new(%w(minutes seconds), [60])
fmt.format(5454) # => "90 minutes, 54 seconds"
fmt.format_string = '%d:%d'
fmt.format(5454) # => "90:54"
Run Code Online (Sandbox Code Playgroud)
请注意,format_string不会让您更改部件的顺序(它始终是最重要的值).对于更细粒度的控制,您可以split自己使用和操作值.
Mik*_*ike 11
需要休息一下.高尔夫球:
s = 270921
dhms = [60,60,24].reduce([s]) { |m,o| m.unshift(m.shift.divmod(o)).flatten }
# => [3, 3, 15, 21]
Run Code Online (Sandbox Code Playgroud)
如果你正在使用Rails,如果你不需要精度,有一个简单的方法:
time_ago_in_words 270921.seconds.from_now
# => 3 days
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35740 次 |
| 最近记录: |