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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With