120

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Yuval Karmi
  • 26,277
  • 39
  • 124
  • 175

7 Answers7

308

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
gunn
  • 8,999
  • 2
  • 24
  • 24
  • @yuval it works on rails and not ruby..Think you have got it but just to help others – SemperFi Jan 28 '14 at 07:09
  • 5
    There is a subtle difference. `Time.now + 10.days` always picks up your system timezone whereas `10.days.from_now` will pick up the UTC timezone if nothing is set in rails config. – Babistalikesflyingonrails Jan 28 '18 at 01:04
  • Generally, it's best to use [`Time.zone.now`](https://robots.thoughtbot.com/its-about-time-zones#a-summary-of-do39s-and-don39ts-with-time-zones) in place of `Time.now`. – x-yuri Aug 08 '18 at 20:44
24

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

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Jonathan Julian
  • 12,163
  • 2
  • 42
  • 48
12

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
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Hieu Pham
  • 6,577
  • 2
  • 30
  • 50
12

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

Date.today + 5
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
dj kaori
  • 121
  • 1
  • 2
7

Try this on Rails

Time.new + 10.days 

Try this on Ruby

require 'date'
DateTime.now.next_day(10).to_time
Rahul Patel
  • 1,386
  • 1
  • 14
  • 16
4

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

DateTime.now.days_since(10)
Ramyani
  • 1,019
  • 1
  • 9
  • 12
0

Little bit difference between:

Time.now + 10.days

3.0.1 :003 > Date.today + 1.day => Wed, 14 Dec 2022

or even

10.days.from_now

3.0.1 :002 > 1.day.from_now => 2022-12-14 15:49:57.35305172 +0600