Get current month / year and next month / year?

I am trying to get all the billing information that has fields corresponding to the current month / year or next year.

For example, let's say that the current month was in December 2014, I would like something like this:

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

This syntax is clearly incorrect, but it gives you an idea of ​​what I need.

So the questions are here ...

  • How to format this request?
  • How to get the current / next month / year for this request format?

I am running Ruby 2.1.2.

+4
source share
3 answers

The Date Ruby class offers many methods:

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)

Do you want it to work with 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)
+4

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

Am I collecting exp_monthand exp_year- integers in your model?

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)
0
source

All Articles