0

How can I get the records that were created_at during the last fully completed week - i.e. between last Monday and last Sunday?

To be absolutely clear, if today was Wednesday 10 July, I would want the records between very early morning Monday 1 July and very late evening Sunday 7 July. If it were Friday 12 July, I would still want the records between Monday 1 July and very late evening Sunday 7 July. But if it was Monday 15 July, I would want records between Monday 8 July and very late evening Sunday 14 July

How can I achieve this?

Note

I can easily get a rolling week's records, i.e. the records between the current time and one week ago (i.e. Time.now - 7.days). This is not what I'm after.

stevec
  • 41,291
  • 27
  • 223
  • 311

2 Answers2

1

You can get last week with Time.now - 7.days, and then get the beginning and end of that week with start_date = (Time.now - 7.days).beginning_of_week and end_date = (Time.now - 7.days).end_of_week.

Then you can query like Model.where('created_at BETWEEN ? AND ?', start_date, end_date).

Jose Manuel
  • 183
  • 7
1
start_date = (Date.today - 1.week).beginning_of_week.beginning_of_day
end_date   = (Date.today - 1.week).end_of_week.end_of_day

Do not forget about timezones if it matters. Good luck

Roman Alekseiev
  • 1,854
  • 16
  • 24