Relative Date Operations

Quick question:

Lets say I have a date as a string such as:

date = '2006-08-24'

Whats the easiest way to change that to a date object and so things
like this:

date.yesterday # which should be 2006-08-24

or

date.tomorrow # should be 2006-08-25

or say

date = '2006-08-31'

date.tomorrow # which should be 2006-09-01

Basically I need to be able to find the previous and next day, for any
date. I know this is probably a simple answer but thanks for any
help/advice in advance

Hi Marston,

Marston wrote:

Lets say I have a date as a string such as:

date = '2006-08-24'

Whats the easiest way to change that to a date object

In Ruby, things are how they behave; not how they're declared. Have you tried to treat 'date' as a Date object? I think you'll be pleasantly surprised. Check out the to_date at http://api.rubyonrails.org/, then fire up script/console and see what you get when you do stuff like new_date = date +1.

hth,
Bill

Quick question:

Lets say I have a date as a string such as:

date = '2006-08-24'

Whats the easiest way to change that to a date object and so things
like this:

date.yesterday # which should be 2006-08-24

or

date.tomorrow # should be 2006-08-25

or say

date = '2006-08-31'

date.tomorrow # which should be 2006-09-01

Basically I need to be able to find the previous and next day, for any
date. I know this is probably a simple answer but thanks for any
help/advice in advance

.to_time

./script/console
Loading development environment.

date = '2006-08-24'.to_time

=> Thu Aug 24 00:00:00 UTC 2006

date.yesterday

=> Wed Aug 23 00:00:00 UTC 2006

date.tomorrow

=> Fri Aug 25 00:00:00 UTC 2006

date.years_since 2

=> Sun Aug 24 00:00:00 UTC 2008

date = '2006-08-31'.to_time

=> Thu Aug 31 00:00:00 UTC 2006

date.tomorrow

=> Fri Sep 01 00:00:00 UTC 2006

Regards,
Rimantas

Thanks a bunch guys, exactly what I needed.