Topic: distance between two DateTime objects in minutes and seconds

if have two dateTime objects.

i need to know the number of seconds, minutes, hours between the two..

how do i do that?

Re: distance between two DateTime objects in minutes and seconds

You can get the hours, minutes and seconds from a date by calling time.hour, time.minute, and time.sec.  So you could do something like this.

a = Time.now
b = 2.minutes.from_now
seconds = b.sec - a.sec
minutes = b.minute - a.minute
hours = b.hour - a.hour

Re: distance between two DateTime objects in minutes and seconds

If you subtract two times it will return the difference in seconds. You can divide it by the number of seconds in a minute/hour/day, etc. like this:

a = Time.now
b = 2.minutes.from_now
b - a # => 120
(b - a)/1.minute # => 2
(b - a)/1.day # => 0.00138...

Railscasts - Free Ruby on Rails Screencasts

Re: distance between two DateTime objects in minutes and seconds

thanks, i found this which works

  def self.distance_between(start_date, end_date)
    difference = end_date.to_i - start_date.to_i
    seconds    =  difference % 60
    difference = (difference - seconds) / 60
    minutes    =  difference % 60
    difference = (difference - minutes) / 60
    hours      =  difference % 24
    difference = (difference - hours)   / 24
    days       =  difference % 7
    weeks      = (difference - days)    /  7
   
    return "#{hours} hours, #{minutes} minutes, #{seconds} seconds"
  end

im only returning hours, minutes, and seconds because that's all i'm interested in for this particular problem.

Last edited by smoothoperatah (2006-12-06 15:57:05)

Re: distance between two DateTime objects in minutes and seconds

Okay, i think you have got your answer about date time objects. Now i am telling you that if you need to know about distance between cities, then you can use distance calculator to measure distance between cities.