Forum: Ruby on Rails Date additon / subtraction - just the basics

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alex T. (Guest)
on 2007-02-08 16:59
How do you manipulate dates?

I take a string x = "2/4/2007".to_date

then I want to add 5 days to it returning "2/9/2007" as a date

I could just pull it apart and add the days to it, but if it should
switch the month then it becomes a problem.

I saw things like 1.week.ago but that deals with the current date, and
x.1.week.ago returns an error.

Thanks for any help.
Ed Hickey (Guest)
on 2007-02-08 17:15
(Received via mailing list)
Try making it a Time object instead of a Date:

>> t = Time.mktime(2007,2,4)
=> Sun Feb 04 00:00:00 CST 2007
>> t.ago(2.days)
=> Fri Feb 02 00:00:00 CST 2007
>> 5.days.since(t)
=> Fri Feb 09 00:00:00 CST 2007

You can call to_date on the Time object if you actually need a Date
object
finally.

ed
James B. (Guest)
on 2007-02-08 17:16
Alex T. wrote:
> How do you manipulate dates?
>
> I take a string x = "2/4/2007".to_date
>
> then I want to add 5 days to it returning "2/9/2007" as a date
>
> I could just pull it apart and add the days to it, but if it should
> switch the month then it becomes a problem.
>
> I saw things like 1.week.ago but that deals with the current date, and
> x.1.week.ago returns an error.
>
> Thanks for any help.


x = x.advance(:days => 5)
James B. (Guest)
on 2007-02-08 17:19
James B. wrote:
should be:

x = x.to_time.advance(:days => 5)
James B. (Guest)
on 2007-02-08 17:20
James B. wrote:
> James B. wrote:
> should be:
>
> x = x.to_time.advance(:days => 5)

and to return a date object

x = x.to_time.advance(:days => 5).to_date
Charly (Guest)
on 2007-02-08 17:27
(Received via mailing list)
check this :
http://errtheblog.com/post/44

x = "2/4/2007".to_time
y = 1.week.ago(x)
z = 2.days.since(x)

Charly
Alex T. (Guest)
on 2007-02-08 18:14
You guys rock!  Thanks for the help!
This topic is locked and can not be replied to.