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.
03d789b32a9e9c47a678f0ac173f5c13?d=identicon&s=25 Alex Treber (Guest)
on 2007-02-08 15: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.
15c80c9bf8be5ba6e5eeac9cb0304464?d=identicon&s=25 Ed Hickey (Guest)
on 2007-02-08 16: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
171ea139761951336b844e708d1547ab?d=identicon&s=25 James Byrne (byrnejb)
on 2007-02-08 16:16
Alex Treber 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)
171ea139761951336b844e708d1547ab?d=identicon&s=25 James Byrne (byrnejb)
on 2007-02-08 16:19
James Byrne wrote:
should be:

x = x.to_time.advance(:days => 5)
171ea139761951336b844e708d1547ab?d=identicon&s=25 James Byrne (byrnejb)
on 2007-02-08 16:20
James Byrne wrote:
> James Byrne 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
3fbe81f6942a6edb382054b2491837f8?d=identicon&s=25 Charly (Guest)
on 2007-02-08 16: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
03d789b32a9e9c47a678f0ac173f5c13?d=identicon&s=25 Alex Treber (Guest)
on 2007-02-08 17:14
You guys rock!  Thanks for the help!
This topic is locked and can not be replied to.