2

I am trying to make a function that can check if a given date is in a specified week ago.

For example, if the input is <1, date object>, then it asks, if the given date is from last week. If the input is <2, date object>, then it asks if the given date is from 2 weeks ago, etc.. (0 is for current week).

Week is Sun-Sat.

    this.isOnSpecifiedWeekAgo = function(weeks_ago, inputDate) {



        return false;
    };

But I don't want to use any libraries, and also I am not sure how to change the week of a date object. Does anyone know how to begin?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

2 Answers2

6

If you want to find out a date that was a week ago, you can simply subtract 7 days from the current date:

var weekAgo = new Date();
weekAgo.setDate(weekAgo.getDate() - 7);
console.log(weekAgo.toLocaleString());

If you want to find out if a date is in a specific week, you'll need to:

  1. Work out the start date for that week
  2. Work out the end date for that week
  3. See if the date is on or after the start and on or before the end

Since your weeks are Sunday to Saturday, you can get the first day of the week from:

var weekStart = new Date();
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
console.log(weekStart.toLocaleString());

The time should be zeroed, then a new date created for 7 days later. That will be midnight at the start of the following Sunday, which is identical to midnight at the end of the following Saturday. So a function might look like:

function wasWeeksAgo(weeksAgo, date) {
  // Create a date
  var weekStart = new Date();
  // Set time to 00:00:00
  weekStart.setHours(0,0,0,0);
  // Set to previous Sunday
  weekStart.setDate(weekStart.getDate() - weekStart.getDay());
  // Set to Sunday on weeksAgo
  weekStart.setDate(weekStart.getDate() - 7*weeksAgo)
  // Create date for following Saturday at 24:00:00
  var weekEnd = new Date(+weekStart);
  weekEnd.setDate(weekEnd.getDate() + 7);
  // See if date is in that week
  return date >= weekStart && date <= weekEnd;
}

 // Test if dates in week before today (1 Nov 2016)
 // 1 Oct            24 Oct
[new Date(2016,9,1), new Date(2016,9,24)].forEach(function(date) {
  console.log(date.toLocaleString() + ' ' + wasWeeksAgo(1, date));
});
RobG
  • 142,382
  • 31
  • 172
  • 209
-1

Use moment.js http://momentjs.com/docs/#/manipulating/subtract/

We use it a lot and its a great lib.

Henry Roeland
  • 492
  • 5
  • 19
  • 1
    Saying "use library X" isn't an answer. Also, the OP says "I don't want to use a library". – RobG Oct 31 '16 at 23:40