54

In C#, There is a method AddDays([number of days]) in DateTime class.

Is there any kind of method like this in ruby?

1
  • 4
    use Rails... You can have something like this t=Time.now; t + 3.days
    – zfm
    Sep 6, 2013 at 12:38

6 Answers 6

94

The Date class provides a + operator that does just that.

>> d = Date.today
=> #<Date: 4910149/2,0,2299161>
>> d.to_s
=> "2009-08-31"
>> (d+3).to_s
=> "2009-09-03"
>> 
0
33

In Rails there are very useful methods of Fixnum class for this (here n is Fixnum. For example: 1,2,3.... ):

Date.today + n.seconds # you can use 1.second
Date.today + n.minutes # you can use 1.minute
Date.today + n.hours # you can use 1.hour
Date.today + n.days # you can use 1.day
Date.today + n.weeks # you can use 1.week
Date.today + n.months # you can use 1.month
Date.today + n.years # you can use 1.year

These are convenient for Time class too.

PS: require Active Support Core Extensions to use these in Ruby

require 'active_support/core_ext'
2
  • 10
    Those methods are Rails-specific
    – Max
    Apr 25, 2014 at 20:23
  • 3
    you can use active support without including the whole Rails framework: gem 'activesupport' require 'active_support' require 'active_support/core_ext' Aug 9, 2018 at 9:40
16

I think next_day is more readable than + version.

require 'date'

DateTime.new(2016,5,17)
# => #<DateTime: 2016-05-17T00:00:00+00:00 ((2457526j,0s,0n),+0s,2299161j)>
DateTime.new(2016,5,17).next_day(10)
# => #<DateTime: 2016-05-27T00:00:00+00:00 ((2457536j,0s,0n),+0s,2299161j)>
Date.new(2016,5,17)
# => #<Date: 2016-05-17 ((2457526j,0s,0n),+0s,2299161j)>
Date.new(2016,5,17).next_day(10)
# => #<Date: 2016-05-27 ((2457536j,0s,0n),+0s,2299161j)>

http://ruby-doc.org/stdlib-2.3.1/libdoc/date/rdoc/Date.html#method-i-next_day.

14

From the Date class:

+(n)

Return a new Date object that is n days later than the current one.

n may be a negative value, in which case the new Date is earlier than the current one; however, #-() might be more intuitive.

If n is not a Numeric, a TypeError will be thrown. In particular, two Dates cannot be added to each other.

5
Date.new(2001,9,01).next_day(30) # 30 - numbers of day 
# => #<Date: 2001-10-01 ...
1
  • Add some explanation with answer for how this answer help OP in fixing current issue May 16, 2016 at 13:01
1

You can also use the advance (https://apidock.com/rails/DateTime/advance) method. I think it's more legible.

date = Date.today
# => Fri, 25 Oct 2019
date.advance(days: 10)
# => Mon, 04 Nov 2019

time = DateTime.now
# => Fri, 25 Oct 2019 14:32:53 +0200
time.advance(months:1, weeks: 2, days: 2, hours: 6, minutes: 6, seconds: 34)
# => Wed, 11 Dec 2019 20:39:27 +0200

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.