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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- .net – 如何将现有的Xml字符串添加到XElement中
- C语言怎么获得进程的PE文件信息
- for-loop – Makefile:for循环和中断错误
- actionscript-3 – FLVPlayback / VideoPlayer:
- objective-c – 是否可以在NSPredicate中使用嵌套
- XML example with Jersey + JAXB
- 利用XStream将List<String>转为xml后指定String的
- ruby-on-rails – 如何设置acts_as_follower
- ruby-on-rails – ActionMailer link_to显示操作
- swift – 类型Array的不可变值只有一个名为’app
热点阅读