加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 获取当前月/年和下个月/年?

发布时间:2020-12-17 03:32:17 所属栏目:百科 来源:网络整理
导读:我正在尝试提取所有包含与当前月/年或下个月匹配字段的结算信息. 例如,假设当前月份是2014年12月,我想要这样的事情: Billing.where(exp_month: 12,exp_year: 2014 OR exp_month: 1,exp_year: 2015) 这种语法显然是不正确的,但它让你知道我在追求什么. 那么,
我正在尝试提取所有包含与当前月/年或下个月匹配字段的结算信息.

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

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

这种语法显然是不正确的,但它让你知道我在追求什么.

那么,这里的问题是……

>如何正确格式化该查询?
>如何获取该查询格式的当前/下个月/年?

我正在运行Ruby 2.1.2.

解决方法

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 ?',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'",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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读