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
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.
-
Sometimes it's worth asking yourself "How would I implement such a feature?" and then take a punt:). Apr 14, 2017 at 20:48
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
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
-
1
10.years
or specificallyyears
is a method added by Rails and not found in plain Ruby. 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