2

Is it possible to subtract one DateTime from another and get the result in Time. Example if we subtract 2011-08-27 01:00:00 UTC from 2011-08-29 08:13:00 UTC, the result should be 55:13:00 (hope I didn't make a mistake while calulating :p) Thanks.

kbaccouche
  • 4,575
  • 11
  • 43
  • 65
  • http://stackoverflow.com/questions/279769/convert-to-from-datetime-and-time-in-ruby – Mchl Aug 24 '11 at 14:58

1 Answers1

6

Time is generally expressed in seconds when doing math like this, even fractional seconds if you want. A Time represents a specific point in time, which while internally represented as seconds since the January 1, 1970 epoch, is not intended to be a scalar unit like that.

If you have two DateTime objects, you can determine the difference between them like this:

diff = DateTime.parse('2011-08-29 08:13:00 UTC').to_time - DateTime.parse('2011-08-27 01:00:00 UTC').to_time
# => 198780.0

Once you have the number of seconds, the rest is simply a formatting problem:

'%d:%02d:%02d' % [ diff / 3600, (diff / 60) % 60, diff % 60 ]
# => "55:13:00"
tadman
  • 208,517
  • 23
  • 234
  • 262
  • Great this is exactly what I want, but I have a small problem, when I do this : diff = DateTime.parse(@project.deadline.to_s).to_time - DateTime.parse(DateTime.now.to_s).to_time with project.deadline.to_s = "2011-08-25T09:25:00+00:00" and DateTime.now.to_s = "2011-08-25T09:24:36+02:00" the result is "2:00:24" While it should be "0:00:24" – kbaccouche Aug 25 '11 at 07:25
  • 1
    Forget about this stupid question, problem fixed. It was because I parsed one more time. Now I'm doing this : diff = @project.deadline.to_s.to_time - DateTime.now.to_s.to_time and it's working perfectly :) Thanks a lot !! – kbaccouche Aug 25 '11 at 07:43