2014-03-19 79 views
2

因此,我決定寫一個腳本,告訴在Unix時間重置之前有多少時間(在32位系統上它是2038年問題,2038-01-19 03:14:07),我覺得很酷它出來了,但這段代碼看起來非常糟糕,我知道有一個更好的方法來做到這一點。我想過使用divmod,但看不出有什麼幫助。這是我的代碼,我很想知道我可以做什麼來重構這個,並提高可讀性。我該如何重構這段代碼才能發現Unix時代的終結?

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" 

回答

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" 
+0

這是偉大的,謝謝!但你能解釋爲什麼2 ** 31 - 1的作品? – Addison

+0

是不是UNIX時間結束的定義?時間只使用正半部。 – sawa

+0

那麼我知道1111etc ...是,但我不知道你怎麼知道如何用2 ** 31 - 1 – Addison