5

In ruby I am using DateTime.now.next_year.to_time to get the time and date of a day one year from now. This now needs to be changed to 10 years. How can I do this.

3 Answers 3

13

This seems to work:

 DateTime.now.next_year(10).to_time
 #=> 2027-04-14 20:40:38 +0000 

Accepts negative numbers too and does what you'd expect.

1
  • Sometimes it's worth asking yourself "How would I implement such a feature?" and then take a punt:). Apr 14, 2017 at 20:48
6

The Date#next_year method takes an argument on how many years to advance

DateTime.now.next_year(10).to_time
#=> 2027-04-14 16:41:09 -0400
4

If you don't mind using ActiveSupport, you can require Time from active support like so:

require "active_support/time"

then you could just do this to get a DateTime object back:

DateTime.now + 10.years
=> Thu, 15 Apr 2027 13:02:15 +0000

or if you want a Time object instead:

DateTime.now.to_time + 10.years
=> 2027-04-15 13:02:15 +0000
2
  • 1
    10.years or specifically years is a method added by Rails and not found in plain Ruby.
    – Leo Correa
    Apr 15, 2017 at 15:21
  • Yes you're right, I'll change my answer to mention that this can be done only if you're using ActiveSupport. Apr 15, 2017 at 15:22

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.