Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby have an equivalent to TimeSpan in C#?

Tags:

ruby

timespan

In C# there is a TimeSpan class. It represents a period of time and is returned from many date manipulation options. You can create one and add or subtract from a date etc.

In Ruby and specifically rails there seems to be lots of date and time classes but nothing that represents a span of time?

Ideally I'd like an object that I could use for outputting formatted dates easily enough using the standard date formatting options.

eg.

ts.to_format("%H%M")

Is there such a class?

Even better would be if I could do something like

   ts = end_date - start_date

I am aware that subtracting of two dates results in the number of seconds separating said dates and that I could work it all out from that.

like image 460
toxaq Avatar asked Jun 19 '12 12:06

toxaq


1 Answers

You can do something similar like this:

irb(main):001:0> require 'time'         => true
irb(main):002:0> initial = Time.now     => Tue Jun 19 08:19:56 -0400 2012
irb(main):003:0> later = Time.now       => Tue Jun 19 08:20:05 -0400 2012
irb(main):004:0> span = later - initial => 8.393871
irb(main):005:0>

This just returns a time in seconds which isn't all that pretty to look at, you can use the strftime() function to make it look pretty:

irb(main):010:0> Time.at(span).gmtime.strftime("%H:%M:%S") => "00:00:08"
like image 169
Hunter McMillen Avatar answered Oct 02 '22 13:10

Hunter McMillen