tags:

views:

62

answers:

2

Does Ruby stdlib have any objects that represent difference between two timestamps? Subtracting two Time object from each other returns a float number of seconds - is there any object for that, with methods like hours, minutes etc., and most of all decent to_s?

I've coded half-assed methods for that far too many time, am I doing it wrong?

+1  A: 

Hi,

perhaps duration does help? Here is an announcement for it.

andyp
+1  A: 

Not in the stdlib, but there is a Gem that you can use for the job - the duration gem.

sudo gem install duration

Which you can use like this:

require "duration"
a = Time.now
sleep(5)
b = Time.now
duration = Duration.new(b - a)
# => #<Duration: 5 seconds>
duration.seconds
# => 5
duration.minutes
# => 0

And days, hours, weeks and a bunch of other useful methods.

You can also then monkey-patch Time, Date and other date-time classes to return Duration objects.

Tom Morris