Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get next/previous month from a Time object

Tags:

ruby

I have a Time object and would like to find the next/previous month. Adding subtracting days does not work as the days per month vary.

time = Time.parse('21-12-2008 10:51 UTC') next_month = time + 31 * 24 * 60 * 60 

Incrementing the month also falls down as one would have to take care of the rolling

time = Time.parse('21-12-2008 10:51 UTC') next_month = Time.utc(time.year, time.month+1)  time = Time.parse('01-12-2008 10:51 UTC') previous_month = Time.utc(time.year, time.month-1) 

The only thing I found working was

time = Time.parse('21-12-2008 10:51 UTC') d = Date.new(time.year, time.month, time.day) d >>= 1 next_month = Time.utc(d.year, d.month, d.day, time.hour, time.min, time.sec, time.usec) 

Is there a more elegant way of doing this that I am not seeing? How would you do it?

like image 211
tcurdt Avatar asked Apr 23 '10 15:04

tcurdt


People also ask

How do I get previous month in react?

Getting the previous month name To get the previous month name, first we need to access the current date object using the new Date() constructor. const current = new Date(); Now, we need to subtract the current month with -1 and set it to the current date using the setMonth() and getMonth() methods.


1 Answers

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 
like image 145
Joshua Pinter Avatar answered Oct 09 '22 05:10

Joshua Pinter