Datetime arithmetic with a string in Ruby

In Ruby, I'm trying to do the following.

def self.stats(since)
  return Events.find(:all, :select => 'count(*) as this_count', :conditions => ['Date(event_date) >= ?', (Time.now - since)]).first.this_count
end

where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?

This question and answers originated from www.stackoverflow.com
Question by (9/2/2008 8:37:53 PM)

Answer

I hacked this together with the ActiveSupport gem:

require 'active_support'

def string_to_date(date_string)
  parts = date_string.split
  return parts[0].to_i.send(parts[1])
end
sinces = ['1 hour', '1 day', '3 days']

sinces.each do |since|
  puts "#{since} ago: #{string_to_date(since).ago(Time.now)}"
end

[edit] To answer your question, you might try it like that:

:conditions => ['Date)event_date) >= ?', (string_to_date(since).ago(Time.now))]
Answer by

Find More Answers
Related Topics  ruby  datetime  time
Related Questions