Ruby, get hours, seconds and time from Date.day
I've found this method here.
start = DateTime.now
sleep 15
stop = DateTime.now
#minutes
puts ((stop-start) * 24 * 60).to_i
hours,minutes,seconds,frac = Date.day_fraction_to_time(stop-start)
I have the following error:
`<main>': private method `day_fraction_to_time' called for Date:Class (NoMethodError)
I've checked /usr/lib/ruby/1.9.1/date.rb and I've found it:
def day_fraction_to_time(fr) # :nodoc:
ss, fr = fr.divmod(SECONDS_IN_DAY) # 4p
h, ss = ss.divmod(3600)
min, s = ss.divmod(60)
return h, min, s, fr * 86400
end
But I have no problem if I run it with ruby1.8. /usr/lib/ruby/1.8/date.rb gives me:
def self.day_fraction_to_time(fr)
ss, fr = fr.divmod(SECONDS_IN_DAY) # 4p
h, ss = ss.divmod(3600)
min, s = ss.divmod(60)
return h, min, s, fr
end
So i went to see the documentation(1.9) and there's no trace of this method. I know it's a dumb question, but why did they remove it? There is even this example on how to use the method in /usr/lib/ruby/1.9.1/date.rb:
def secs_to_new_year(now = DateTime::now())
new_year = DateTime.new(now.year + 1, 1, 1)
dif = new_year - now
hours, mins, secs, ignore_fractions = Date::day_fraction_to_time(dif)
return hours * 60 * 60 + mins * 60 + secs
end
but I'm still getting the error:
test.rb:24:in `secs_to_new_year': private method `day_fraction_to_time' called for Date:Class (NoMethodError)
from test.rb:28:in `<main>'
I don't know why it was made private, but you can still access it:
hours,minutes,seconds,frac = Date.send(:day_fraction_to_time, stop-start)
This way you override the OOP encapsulation mechanizm... This is not a very nice thing to do, but it works.
I've found another method which seems more elegant to me:
start = DateTime.now
sleep 3
stop = DateTime.now
puts "Date.day_fraction_to_time using wrapper"
class Date
class << self
def wrap_day_fraction_to_time( day_frac )
day_fraction_to_time( day_frac )
end
end
end
hours, minutes, seconds, frac =
Date.wrap_day_fraction_to_time( stop - start )
p hours, minutes, seconds, frac
Thanks to Colin Bartlett from ruby-forum.com
To understand how it works I suggest to read David Seiler's answer
链接地址: http://www.djcxy.com/p/2802.html