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"
How can I refactor this code that finds the end of Unix time?
-
17-06-2023 - |
Pergunta
So I decided that I would be cool to make a script that tells how much time there is until Unix time resets (on 32 bit systems its the year 2038 problem, 2038-01-19 03:14:07) and I figured it out, but this code looks really awful and I know there has got to be a better way to do this. I thought about using divmod, but couldn't see how that'd help. Here is my code, and I'd love to know what I can do to refactor this, and improve readability.
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"
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow