This might help for calculating days ago:
irb(main):001:0> require 'date'
irb(main):002:0> t = Date.today
=> #<Date: 4908063/2,0,2299161>
irb(main):004:0> puts t
irb(main):005:0> puts t - 7
I think you can just use the << or >> as in:
irb(main):001:0> require "Date"
irb(main):002:0> d = Date.new(1997, 12, 31)
=> #<Date: 4901627/2,0,2299161>
irb(main):004:0> d2 = d >> 1
=> #<Date: 4901689/2,0,2299161>
irb(main):006:0> d2 = d >> 2
=> #<Date: 4901745/2,0,2299161>
irb(main):008:0> d2 = d << 1
=> #<Date: 4901565/2,0,2299161>
And I think Date is already included in Rails controllers so you don't
need to do the include.
@time.advance :months => 7
@time.advance :days => -15
Frederick Cheung wrote:
> days_ago and weeks_ago aren't there because they are easy: days_ago is
> just n * 86400 seconds ago, so you can just write 3.days.ago
> months_ago is more complicated because of the varying numbers of day in
> a month, you need to now what the value of now is, which is why we have
> months_ago, months_since
> A word of warning about Date, Date can be quite slow compared to Time.
> Most of the time you won't care, but I was writing a calendaring style
> app that did a lot of that sort of calculations and using profiling
> showed that the various Date operations were a big slowdown
Can someone elaborate on the Date Vs Time speed comment?
I am about to write a lot of calendar like functionality that doesn't
really need hour/minute level details and was thinking using Date
throughout. But if it means taking a performance hit, I will reconsider.
Posted via http://www.ruby-forum.com/.
Simply put, Time values are stored as a long integer and all math on
them is done by adding or subtracting two values. This is very fast.
Date does a bunch of processing to make sure things work fine, which is
require 'ruby-units' (gem for unit conversions and unit math)
require 'chronic' (interprets natural language time specs)
'2 weeks'.from 'today'
#=> Mon Nov 06 17:00:00 EST 2006
'2 weeks'.from 'today'.to_date
also does... 'ago', 'from', 'until', etc...
but ruby-units doesn't do months since they aren't a fixed size
It does contain a number of helpers for converting back and forth
between time and date objects, and it will automatically convert to a
date object if any math you do takes you outside the normal range for a
for more about ruby-units see