鉴于时间戳,如何获得1个月前

时间:2013-04-02 04:34:07

标签: ruby-on-rails ruby-on-rails-3

我正在尝试构建一种方法,我会传递一个月,然后可以动态查询上个月。

total_churn(month)
   last_month = month - 1
   companies = Company.where("created_at BETWEEN '#{last_month}' AND '#{month}')
   return companies.count
 end

如何以一种方式传递方法'月',我可以使用ruby on rails动态确定上个月?感谢

3 个答案:

答案 0 :(得分:2)

My suggestion: accept a date rather than a month.
total_churn(date)
   month_previous = date - 1.month
   companies = Company.where("created_at BETWEEN ? AND ?, '#{month_previous}', '#{date}')
   return companies.count
end

Current month:
Time.now.month
Date.today.month

Time or day one month ago:
(Time.now - 1.month).month
(Date.today - 1.month).month

...also equivalent to:
Time.now.month - 1
Date.today.month - 1

Previous month for any given date:
@date - 1.month

我个人会建立你的方法来接受一个日期,而不仅仅是一个月的数字。只要created_at字段存储日期,您就需要为查询提供两个日期才能运行,即使这些日期是第一个。

答案 1 :(得分:1)

Rails有一些有用的时间助手来为您的查询创建上限和下限。 (Time class

中的beginning_of_monthend_of_month

此方法也可以使用问号进行正确转义,而不是字符串插值,这对SQL注入攻击是开放的。

def total_churn(month)
  companies = Company.where('created_at BETWEEN ? and ?',(Time.now - 1.month).beginning_of_month,(Time.now - 1.month).end_of_month)
  companies.count
end

我还会说这只适用于最近一年。如果您希望能够查询早期数据,您可能想要添加年份参数或只是传递一个日期并让它使用它来代替Time.now

# with separate year and month params
def total_churn(month, year)
  date = DateTime.parse("#{year}/#{month}/01")
  companies = Company.where('created_at BETWEEN ? and ?',(date - 1.month).beginning_of_month,(date - 1.month).end_of_month)
  companies.count
end

# with a random date input
def total_churn(date_in_month)
  companies = Company.where('created_at BETWEEN ? and ?',(date_in_month - 1.month).beginning_of_month,(date_in_month - 1.month).end_of_month)
  companies.count
end

答案 2 :(得分:0)

您需要至少2个参数来完成此操作,一个用于月份,一个用于年份。这需要确定你想要的月份。

def total_churn(year, month)
  date = Date.new year, month
  one_month_ago = date - 1.month
  ...

但是,如果您已有日期对象,则可以使用sscirrus'回答。如果日期在字符串中,您可能需要先解析它(如在评论中)

def total_churn(date_string)
  date = Date.parse(date_string)
  one_month_ago = date - 1.month
  ...

>> date_string = '2012-09-01 00:00:00.000000'
>> total_churn date_string