I want to get exact time in days and hours between two dates something like between Thu Jul 18 11:30:00 +0000 2013
and Sat Jul 20 10:30:00 +0000 2013
. There is difference of 1 day and 23 hours
. The Rails' ActionView module includes two methods
(1) distance_of_time_in_words
(2) distance_of_time_in_words_to_now
but they return result like 1 day or 2 day i need hours also.
If you don't want to use any gem then you can simply do following calculations to get exact difference of minutes and seconds too -
t1 = Time.now #date1
t2 = (Time.now - 10.hours) #date2
seconds = (t1.to_i - t2.to_i)
days = seconds / 86400;
hours = seconds / 3600;
minutes = (seconds - (hours * 3600)) / 60;
seconds = (seconds - (hours * 3600) - (minutes * 60));
The plugin dotiw might be useful to solve this issue.
dotiw is a plugin for Rails that overrides the default distance_of_time_in_words and provides a more accurate output.
There's a gem for that: time_diff
!
https://rubygems.org/gems/time_diff
It will display the time difference and you can even format the output. Example:
'%y, %M, %w, %d and %h:%m:%s'
will return: '1 year, 2 months, 3 weeks, 4 days and 12:05:52'
The syntax is also very straighforward:
> Time.diff(Time.parse('2010-03-06 12:30:00'), Time.parse('2011-03-07 12:30:30'), '%y, %d and %h:%m:%s')
=> {:year => 1, :month => 0, :week => 0, :day => 0, :hour => 18, :minute => 0, :second => 30, :diff => '1 year and 18:00:30'}
You should be able to get what you need out of this.
Happy coding !
date_1 = DateTime.parse("Thu Jul 18 11:30:00 +0000 2013")
date_2 = DateTime.parse("Sat Jul 20 10:30:00 +0000 2013")
difference_in_hours = (date_2.to_time - date_1.to_time) / 60 / 60
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.