get next/previous month from a Time object

Personally I prefer using:

Time.now.beginning_of_month - 1.day      # previous month
Time.now.end_of_month + 1.day            # next month

It always works and is independent from the number of days in a month.

Find more info in this API doc


you can use standard class DateTime

require 'date'

dt = Time.new().to_datetime
=> #<DateTime: 2010-04-23T22:31:39+03:00 (424277622199937/172800000,1/8,2299161)>

dt2 = dt >> 1
=> #<DateTime: 2010-05-23T22:31:39+03:00 (424282806199937/172800000,1/8,2299161)>

t = dt2.to_time
=> 2010-05-23 22:31:39 +0200

Ruby on Rails

Note: This only works in Rails (Thanks Steve!) but I'm keeping it here in case others are using Rails and wish to use these more intuitive methods.

Super simple - thank you Ruby on Rails!

Time.now + 1.month

Time.now - 1.month  

Or, another option if it's in relation to the current time (Rails 3+ only).

1.month.from_now

1.month.ago

Tags:

Ruby