Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby add a calendar month

Tags:

date

ruby

Am new to ruby, and having an issue with some date functions. I am trying to add a calendar month to a supplied date, so that "30th Apr 2002", would output "31st May 2002". Here is my code

 date = '30th Apr 2002'
 parseDate = Date.parse(date)

(parseDate >> 1) # This returns 2002-05-30

Maybe this is not how the function is supposed to work, in which case I would need to write some code to return the last day of the next month, if the supplied date is the last day of the month?

Any help would be appreciated thanks.

like image 899
namtax Avatar asked Nov 07 '11 10:11

namtax


1 Answers

The >> does just increment the month and keep the same day within the month, which as Skeet noted in a comment is somewhat sensible...

But to get the behavior you want, you can just add and subtract a day in the right order to take the last day across the month boundary and back:

((parseDate +1) >> 1) - 1

For subtracting months, as it appears from comments you really want, use the same trick but the reverse month operator.

((parseDate +1) << 1) - 1
like image 65
Don Roby Avatar answered Sep 18 '22 13:09

Don Roby