How to get today the day of the previous month in ruby?

Is there a built-in function to get the day in the last month, like today? Examples:

2010/05/02 -> 2010/04/02 2010/05/15 -> 2010/04/15 2010/05/31 -> 2010/04/30 

Thanks!

+4
source share
5 answers

You can subtract whole months with << .

 >> d = Date.parse('2010-05-31') => #<Date: 4910695/2,0,2299161> >> d.to_s => "2010-05-31" >> (d<<1).to_s => "2010-04-30" 

Additional Information

+11
source

You can try using

Time.parse('2010/05/31').months_since(-1) .

+3
source

You can do it:

 (Date.today - 1.month).strftime("%Y/%m/%d") 
+3
source

You can, for example, create a time object

 old_time = Time.now 

Then create a new time object based on this

 new_time = Time.local(old_time.year, (old_time.month - 1), old_time.day, old_time.hour, old_time.min, old_time.sec) 

However, as deceze pointed out, what is the criterion for 5/31 that becomes 4/30? In irb, 4/31 'overflows' to 5/01.

+1
source

Ruby date class allows you to add, subtract days from a specific date.

0
source

Source: https://habr.com/ru/post/1309281/


All Articles