获取当前月/年和下个月/年?

时间:2014-07-21 13:28:33

标签: ruby-on-rails ruby

我试图提取所有包含与当前月/年或下个月匹配字段的结算信息。

例如,假设当前月份是2014年12月,我想要这样的事情:

Billing.where(exp_month: 12, exp_year: 2014 OR exp_month: 1, exp_year: 2015)

这种语法显然是不正确的,但它可以让你了解我之后的情况。

所以,这里的问题是......

  1. 如何正确格式化该查询?
  2. 如何获取该查询格式的当前/下个月/年?
  3. 我正在运行Ruby 2.1.2。

3 个答案:

答案 0 :(得分:5)

Ruby的Date类提供了很多方法:

first_of_month = Date.current.beginning_of_month
last_of_next_month = (Date.current + 1.months).end_of_month
Billing.where('your_date_field BETWEEN ? AND ?', first_of_month, last_of_next_month)

您希望它与DateTime一起使用吗?

first_of_month = Date.current.beginning_of_month.beginning_of_day
last_of_next_month = (Date.current + 1.months).end_of_month.end_of_day
Billing.where('your_date_field BETWEEN ? AND ?', first_of_month, last_of_next_month)

如果你想要更复杂的东西,我建议你使用PostgreSQL的日期/时间函数:http://www.postgresql.org/docs/9.1/static/functions-datetime.html

conditions = []
conditions << ["date_part('year', your_date_field) = '2014'", "date_part('month', your_date_field) = '12')"]
conditions << ["date_part('year', your_date_field) = '2015'", "date_part('month', your_date_field) = '01')"]
conditions = conditions.map do |conds|
  " ( #{conds.join(' AND ')} ) "
end.join(' OR ')
# => " ( date_part('year', your_date_field) = '2014' AND date_part('month', your_date_field) = '12') )  OR  ( date_part('year', your_date_field) = '2015' AND date_part('month', your_date_field) = '01') ) "
Billing.where(conditions)

答案 1 :(得分:2)

你可以试试这个

 Date.today.strftime("%m") # for month
 Date.today.strftime("%Y") # for year

答案 2 :(得分:0)

我在模型中收集exp_monthexp_year是否为整数?

Billing.where("(exp_month = ? AND exp_year = ?) OR (exp_month = ? AND exp_year = ?)", Date.today.month, Date.today.year, (Date.today + 1.month).month, (Date.today + 1.month).year)