Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the dates for the same week a year ago?

This is an example of a week, from Sunday to Saturday:

11/21/2010 - 11/27/2010

I would like to find the dates for the same week Sunday-Saturday, only for last year.

like image 419
fenec Avatar asked Dec 01 '10 21:12

fenec


Video Answer


2 Answers

require 'date' # Included in Ruby's standard library, no gem needed
now = Date.today
before = Date.civil( now.year-1, now.month, now.day )
sunday = Date.commercial( before.year, before.cweek, 1 ) - 1 # Day 1 is Monday
this_week_last_year = sunday..(sunday+6)

Edit: Though Date.commercial is cool, it's not needed. Here's a Simpler way to find the Sunday starting the week:

require 'date'
now    = Date.today
before = Date.civil( now.year-1, now.month, now.day )
sunday = before - before.wday
like image 173
Phrogz Avatar answered Sep 23 '22 18:09

Phrogz


>> 1.year.ago.beginning_of_week.to_date
Mon, 30 Nov 2009
>> 1.year.ago.end_of_week.to_date
Sun, 06 Dec 2009
like image 45
Chirantan Avatar answered Sep 24 '22 18:09

Chirantan