Reputation: 240
I have two dates: start date
and end date
. I want to calculate the number of days between end date
and start date
. If start date
is 1-11-2011
, end date
is 2-11-2012
, and I put start date - end date
, it will show the number of days as 1
, and will not count the months and years. How can I do this in ruby? Kindly help me.
Upvotes: 1
Views: 1697
Reputation: 1389
Try this.
time_ago_in_words(pending_requests.created_at)
This will take care of days and hours both like for example
about 17 hours ago
and
3 days ago
Upvotes: 1
Reputation: 4698
require 'date'
start_date = Date.parse('1-11-2011')
# => #<Date: 2011-11-01 … >
end_date = Date.parse('2-11-2012')
# => #<Date: 2012-11-02 … >
inclusive_days_in_range = (start_date .. end_date).count
# => 368
Or if you care about efficiency (two orders of magnitude faster):
inclusive_days_in_range = (end_date - start_date) + 1
# => 368
Please note that if you use Date.parse
, the given date string like yours will be interpreted as if it begins with the day and is followed by month and year. If that is not what you want, you must use the Date.strptime
method to manually specify your date format, even if I don't know of any nation on Earth where this would be the conventional date format. To be clear and avoid string parsing you could also initialize Date objects the following way:
Date.new(2012, 1, 11)
Another good idea would be to use ISO-8601 (YYYY-MM-DD) format in your application internals and only convert them into localized representations on demand to improve clarity.
Upvotes: 4
Reputation: 168101
require "date"
(
Date.strptime("2-11-2012", "%m-%d-%Y") -
Date.strptime("1-11-2011", "%m-%d-%Y")
).to_i + 1
# => 397
Upvotes: 5