Ruby中带字符串的日期时间算术

时间:2020-03-05 18:46:43  来源:igfitidea点击:

在Ruby中,我正在尝试执行以下操作。

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

其中," since"是代表时间量(" 1小时"," 1天"," 3天")的字符串,依此类推。有什么建议?

解决方案

回答

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

回答

我将其与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

[编辑]要回答问题,我们可以这样尝试:

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