Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get today's day of previous month in ruby?

Tags:

ruby

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

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

Thanks!

like image 822
ohho Avatar asked May 10 '10 03:05

ohho


3 Answers

You can subtract entire 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"

More info

like image 60
theIV Avatar answered Oct 18 '22 20:10

theIV


You could do this:

(Date.today - 1.month).strftime("%Y/%m/%d")
like image 4
dennismonsewicz Avatar answered Oct 18 '22 19:10

dennismonsewicz


You can try using

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

like image 3
Richie Min Avatar answered Oct 18 '22 20:10

Richie Min