tags:

views:

69

answers:

3

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!

A: 

Ruby's date class allows you to add, subtract days from a particular date.

Sid H
+1  A: 

You could for instance make a time object

old_time = Time.now

Then create a new time object based on that

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 becoming 4/30? In irb, 4/31 'overflows' to 5/01.

Robbie
+6  A: 

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

theIV
wonderful! didn't notice there is a '<<' at all.
ohho
Nor had I until a few weeks ago. As I'm sure you can tell from the documentation on `Date` there's also a `>>` if you are going in the other direction.
theIV