Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract n months from a DateTime in Ruby?

Tags:

datetime

ruby

I'm new in ruby and date arithmetics seems confusing.

How can I remove n months from a DateTime without using any other modules?

like image 565
aclowkay Avatar asked Feb 20 '18 14:02

aclowkay


1 Answers

Since DateTime is a subclass of Date, you can use << or prev_month:

require 'date'

d = DateTime.now    #=> #<DateTime: 2018-02-20T15:39:44+01:00 ...>
d << 4              #=> #<DateTime: 2017-10-20T15:39:44+01:00 ...>
d.prev_month(4)     #=> #<DateTime: 2017-10-20T15:39:44+01:00 ...>

Note that DateTime doesn't account for daylight savings time.

like image 164
Stefan Avatar answered Nov 14 '22 21:11

Stefan