Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - rails - subtract date time

Is there a method in ruby/rails for adding/subtracting date and time along with timezone and the output to be as count of days, hours, minutes and seconds instead of DataTime format?

t1 = "2012-05-05 00:00:02 -0400"
t2 = "2012-05-04 00:00:00 -0500"

time_diff = (Time.now() - Time.parse(t1)).to_s
#Or
time_diff = (Time.parse(t1) - Time.parse(t2)).to_s

I am looking for 1 Day, 01:59:58 The result should #of Days HH:MM:SS format

like image 686
Majoris Avatar asked Feb 19 '26 00:02

Majoris


1 Answers

As far as I know there's nothing built-in to Ruby or Rails to do this. There is distance_of_time_in_words, but it gives a fuzzier time than you seem to be looking for (e.g. "about 7 days").

It's fairly trivial to write a method to do this, though. Given a difference in seconds, this will give you the days, hours, and seconds in the difference:

def time_length seconds
  days = (seconds / 1.day).floor
  seconds -= days.days
  hours = (seconds / 1.hour).floor
  seconds -= hours.hours
  minutes = (seconds / 1.minute).floor
  seconds -= minutes.minutes
  { days: days, hours: hours, minutes: minutes, seconds: seconds }
end

time_length(Time.parse(t1) - Time.parse(t2))
#=> {:days=>0, :hours=>23, :minutes=>0, :seconds=>2.0}
like image 170
Andrew Marshall Avatar answered Feb 21 '26 15:02

Andrew Marshall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!