简体   繁体   中英

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?

尝试使用“ 慢性”将日期字符串解析为实际的datetime对象。

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))]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM