所以我决定制作一个脚本,告诉我有多少时间,直到Unix时间重置(在32位系统上它是2038年的问题,2038-01-19 03:14:07)我会很酷想通了,但这段代码看起来非常糟糕,我知道必须有更好的方法来做到这一点。我想过使用divmod,但是看不出有什么帮助。这是我的代码,我很想知道如何重构这一点,并提高可读性。
time = Time.now
end_of_unix_time = Time.gm(2038, 1, 19, 3, 14, 7).getlocal
diff = end_of_unix_time - time
years = (diff / 60 / 60 / 24 / 365).floor
days = (diff / 60 / 60 / 24 - (years * 365)).floor
hours = (diff / 60 / 60 - (years * 365 * 24) - (days * 24)).floor
min = (diff / 60 - (years * 365 * 24 * 60) - (days * 24 * 60) - (hours * 60)).floor
sec = (diff - (years * 365 * 24 * 60 * 60) - (days * 24 * 60 * 60) - (hours * 60 * 60) - (min * 60)).floor
puts "#{years} years"
puts "#{days} days"
puts "#{hours} hours"
puts "#{min} minutes"
puts "#{sec} seconds"
答案 0 :(得分:2)
end_of_unix_time = Time.at(2 ** 31 - 1)
diff = end_of_unix_time - Time.now
years, days, hours, min, sec =
[60, 60, 24, 365].each_with_object([diff]){|d, a| a[0..0] = a[0].divmod(d)}
puts "#{years} years"
puts "#{days} days"
puts "#{hours} hours"
puts "#{min} minutes"
puts "#{sec} seconds"