Datetime arithmetic with a string in Ruby
Question
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?
Solution
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))]
OTHER TIPS
Try using Chronic to parse the date strings into actual datetime objects.
I agree with John Millikin. Chronic, or even your own helpers, would be a much lighter and effective dependency to carry than whole ActiveSupport, assuming you are not already trapped inside Rails.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow