In Rails, display time between two dates in English
The other answers may not give the type of output that you're looking for, because instead of giving a string of years, months, etc., the Rails helpers just show the largest unit. If you're looking for something more broken down, here's another option. Stick this method into a helper:
def time_diff_in_natural_language(from_time, to_time)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_seconds = ((to_time - from_time).abs).round
components = []
%w(year month week day).each do |interval|
# For each interval type, if the amount of time remaining is greater than
# one unit, calculate how many units fit into the remaining time.
if distance_in_seconds >= 1.send(interval)
delta = (distance_in_seconds / 1.send(interval)).floor
distance_in_seconds -= delta.send(interval)
components << pluralize(delta, interval)
# if above line give pain. try below one
# components << interval.pluralize(delta)
end
end
components.join(", ")
end
And then in a view you can say something like:
<%= time_diff_in_natural_language(Time.now, 2.5.years.ago) %>
=> 2 years, 6 months, 2 days
The given method only goes down to days, but can be easily extended to add in smaller units if desired.
In Rails, display time between two dates in English
The other answers may not give the type of output that you're looking for, because instead of giving a string of years, months, etc., the Rails helpers just show the largest unit. If you're looking for something more broken down, here's another option. Stick this method into a helper:
def time_diff_in_natural_language(from_time, to_time)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_seconds = ((to_time - from_time).abs).round
components = []
%w(year month week day).each do |interval|
# For each interval type, if the amount of time remaining is greater than
# one unit, calculate how many units fit into the remaining time.
if distance_in_seconds >= 1.send(interval)
delta = (distance_in_seconds / 1.send(interval)).floor
distance_in_seconds -= delta.send(interval)
components << pluralize(delta, interval)
# if above line give pain. try below one
# components << interval.pluralize(delta)
end
end
components.join(", ")
end
And then in a view you can say something like:
<%= time_diff_in_natural_language(Time.now, 2.5.years.ago) %>
=> 2 years, 6 months, 2 days
The given method only goes down to days, but can be easily extended to add in smaller units if desired.
Exact Difference between two dates in days and hours
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 !
Find number of months between two Dates in Ruby on Rails
(date2.year * 12 + date2.month) - (date1.year * 12 + date1.month)
more info at http://www.ruby-forum.com/topic/72120
Compare two dates from two different sources
- For simple comparison, use
object.created_at.zone.eql? object2.created_at.zone
To cast to the same timezone, you can useTime.parse(object.created_at).in_time_zone(object2.created_at.zone)
- You can convert your date to UNIX time format,
object.created_at.to_i - object2.created_at.to_i
is the difference in seconds, if necessary, you can calculate in hours and days by dividing by 60 and then by 24. I suggest immediately using the calculation in modules , since we do not know in advance which object was created later.
Rails, Ruby, Calculate Days between Dates + auto form population
Your form is most likely going to post to save data in rows of your database that represent an instance of a model. So you can use a model method (or, since some would argue that models should only contain persistence logic, a model decorator) to achieve this. For now, it's easiest to keep it in the model.
Say your model name is Event.
Then you can have start_date
and end_date
fields on it. These will likely be datetime
fields.
Then, you can have a method in your model called, say, days_spread
:
def days_spread
end_date.to_date - start_date.to_date
end
Calling to_date
on those datetimes will make the result of that subtraction a number of days. You may also need to call to_i
on that return value to get an integer.
Then you can just call days_spread.times do { |x| }
It's hard to give you a more specific answer without your data model, but that should get you started.
Iterating between two DateTimes, with a one hour step
Similar to my answer in "How do I return an array of days and hours from a range?", the trick is to use to_i
to work with seconds since the epoch:
('2013-01-01'.to_datetime.to_i .. '2013-02-01'.to_datetime.to_i).step(1.hour) do |date|
puts Time.at(date)
end
Note that Time.at()
converts using your local time zone, so you may want to specify UTC by using Time.at(date).utc
How to know if today's date is in a date range?
Use ===
Actually, there is an operator that will do this. Make a Range
and compare Time
objects to it using the ===
operator.
start = Time.now.to_i
range = start..(start + 2)
inside = start + 1
outside = start + 3 # ok, now...
range === inside # true
range === outside # false
Update post-comment-flood: This version works well everywhere. (In Rails, in Ruby 1, and in Ruby 2.) The earlier
irb
example also worked fine but the interactive example wasn't always reproduced correctly in some experiments. This one is easier to cut-and-paste.It's all straightened out now.
Related Topics
How to Compare Strings Ignoring the Case
Given an Array of Arguments, How to Send Those Arguments to a Particular Function in Ruby
Sum the Value of Array in Hash
How to Use Bundler with Offline .Gem File
Using Join Tables in Ruby on Rails
How to Check If a Value Is a Number
What Does the "$" Character Mean in Ruby
Error: SASS Installation for Windows
How to Configure Ruby on Rails with Oracle
How to Count the Number of Records That Have a Unique Value in a Particular Field in Ror
How to Select Every Nth Item in an Array
Ruby: File Encryption/Decryption with Private/Public Keys
Confusion About Passing Instance Variables to Redirect_To Method. as Seen in Rails Guides
Ruby - Lexical Scope VS Inheritance
How to Combine Overlapping Time Ranges (Time Ranges Union)