How to add 10 days to current time in Rails

Ruby on-RailsDatetimeRuby on-Rails-3Activesupport

Ruby on-Rails Problem Overview


I tried doing something like

Time.now + 5.days

but that doesn't work, even though I vaguely remember seeing, and being very impressed, with being able to do something like 2.years etc.

How do I do that in Rails 3?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Use

Time.now + 10.days

or even

10.days.from_now

Both definitely work. Are you sure you're in Rails and not just Ruby?

If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.

Solution 2 - Ruby on-Rails

days, years, etc., are part of Active Support, So this won't work in irb, but it should work in rails console.

Solution 3 - Ruby on-Rails

This definitely works and I use this wherever I need to add days to the current date:

Date.today + 5

Solution 4 - Ruby on-Rails

Some other options, just for reference

-10.days.ago
# Available in Rails 4
DateTime.now.days_ago(-10)

Just list out all options I know:

[1] Time.now + 10.days
[2] 10.days.from_now
[3] -10.days.ago
[4] DateTime.now.days_ago(-10)
[5] Date.today + 10

So now, what is the difference between them if we care about the timezone:

  • [1, 4] With system timezone
  • [2, 3] With config timezone of your Rails app
  • [5] Date only no time included in result

Solution 5 - Ruby on-Rails

Try this on Rails

Time.new + 10.days 

Try this on Ruby

require 'date'
DateTime.now.next_day(10).to_time

Solution 6 - Ruby on-Rails

Try this on Ruby. It will return a new date/time the specified number of days in the future

DateTime.now.days_since(10)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuval KarmiView Question on Stackoverflow
Solution 1 - Ruby on-RailsgunnView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJonathan JulianView Answer on Stackoverflow
Solution 3 - Ruby on-Railsdj kaoriView Answer on Stackoverflow
Solution 4 - Ruby on-RailsHieu PhamView Answer on Stackoverflow
Solution 5 - Ruby on-RailsRahul PatelView Answer on Stackoverflow
Solution 6 - Ruby on-RailsRamyaniView Answer on Stackoverflow