How to add 3 calendar months to a Time attribute?

I thought this might be easy, but unless I'm missing something it's not so straightforward...

I have a datetime attribute and I want to add n Calendar months to it. How do I do that?

Thanks in advance,

Matt.

Time.now + 3.months

or…

model[:some_date] += 3.months

you’ll need to handle the year boundaries yourself

thanks Ian.

I got "NoMethodError: undefined method `months' for 3:Fixnum" trying to run that snippet of code (I tried in irb too).

I finally ended up with this. It seems to handle year boundaries, too. Hopefully someone else will find it useful:

pd = DateTime.new(*ParseDate.parsedate(@ad.starts_at.to_s)[0..4]) @ad.ends_at = ea>>(3*@ad.listing_period_quarters.to_i)

Cheers,

Matt.

Using 3 months as an example...

Add 3 months: time >> 3

Subtract 3 months: time << 3

Test with: ruby -r date -e 'puts (DateTime.now() >> 3).strftime("%m/%d/%Y")'

Don't try using "3.months", as it'll add 90 days which is guaranteed to be incorrect. It also has issues since 3.months simply returns the integer 7776000, which is the number of seconds in 90 days (60*60*24*30*3). If you try adding that to a "Date" value instead of a "DateTime" value, you'll get something really wacky since "Date" objects view integers as a number of days rather than seconds. ">>" and "<<" work the same for both Date's and DateTime's.

Date/time arithmetic is awesomely easy in Ruby, just read up on the Date class at www.ruby-doc.org/core/.

Michael

I thought this might be easy, but unless I'm missing something it's not so straightforward...

I have a datetime attribute and I want to add n Calendar months to it. How do I do that?

Thanks in advance,

Using 3 months as an example...

Add 3 months: time >> 3

Subtract 3 months: time << 3

Test with: ruby -r date -e 'puts (DateTime.now() >> 3).strftime("%m/%d/%Y")'

That was just what I was looking for.

Date/time arithmetic is awesomely easy in Ruby, just read up on the Date class at www.ruby-doc.org/core/.

I had a feeling it would be, hence the question! I did look around the RoR api docs but didn't see anything which looked useful. I noticed months_since etc after someone pointed it out to me, and I am using that in Rails, but knowing this will be handy outside of Rails, too!

I'm pretty new to Ruby and it impresses me more every day.

Thanks very much!

Matt.