Forum: Ruby time difference calcualtion

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8d6f5daee16e380ce0ac00395b417fb6?d=identicon&s=25 uval (Guest)
on 2005-12-07 04:33
(Received via mailing list)
Hello,

I would like to calculate the difference between two times in seconds
eg

Fri Dec  2 03:12:19 2005
Fri Dec  2 14:44:47 2005

I took a look at Time.singleton_methods but they dont seem apropriate
for this conversion

since I am quite new to Ruby I dont know its libraries or where to
search

thx in advance

Regards, Daniel
C1bcb559f87f356698cfad9f6d630235?d=identicon&s=25 hal9000 (Guest)
on 2005-12-07 04:57
(Received via mailing list)
Daniel Schüle wrote:
>
> I would like to calculate the difference between two times in seconds

require 'time'
t1 = Time.parse("Fri Dec  2 03:12:19 2005")
t2 = Time.parse("Fri Dec  2 14:44:47 2005")

diff = t2 - t1     # diff in seconds



Hal
1279eedc4a964ac0e75ce8ce33e84178?d=identicon&s=25 dave.burt (Guest)
on 2005-12-07 05:21
(Received via mailing list)
Daniel Schüle wrote:
>
> since I am quite new to Ruby I dont know its libraries or where to search

require 'date'
(DateTime.parse("Fri Dec  2 03:12:19 2005") - DateTime.parse("Fri Dec
2 14:44:47 2005")) * 24 * 60 * 60  #=> -41548

Look up the Time, DateTime and Date classes on http://ruby-doc.org/core
for related info.

Cheers,
Dave
B0dfbb957a5df608772f74add7e62df1?d=identicon&s=25 ABHILASH M.A (abhidsm)
on 2011-03-09 17:08
uval wrote in post #8566:
> Hello,
>
> I would like to calculate the difference between two times in seconds
> eg
>
> Fri Dec  2 03:12:19 2005
> Fri Dec  2 14:44:47 2005
>
> I took a look at Time.singleton_methods but they dont seem apropriate
> for this conversion
>
> since I am quite new to Ruby I dont know its libraries or where to
> search
>
> thx in advance
>
> Regards, Daniel

Try https://rubygems.org/gems/time_diff

which returns the difference in a hash
Ca8efd0ba834b02b9b7dd34b5c6c2721?d=identicon&s=25 Kirk Haines (Guest)
on 2011-03-09 17:36
(Received via mailing list)
> uval wrote in post #8566:
>> Hello,
>>
>> I would like to calculate the difference between two times in seconds
>> eg
>>
>> Fri Dec 2 03:12:19 2005
>> Fri Dec 2 14:44:47 2005

Just keep it simple.  You can do math with Time objects, and the unit
of time for a Time object is the second.  So, turn your dates into
Time objects:

require 'time'
first = Time.parse('Fri Dec  2 03:12:19 2005')
second = Time.parse('Fri Dec  2 14:44:47 2005')

Then subtract one from the other:

difference = second - first


Kirk Haines
Software Engineer
EngineYard
This topic is locked and can not be replied to.