开发者

Representing time differences in Ruby

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 me开发者_StackOverflowthods for that far too many time, am I doing it wrong?


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.


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


There is a gem called time_diff which return a hash of difference in year, month, week, day, hour, minute, second

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜