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
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:
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)); });
Use moment.js http://momentjs.com/docs/#/manipulating/subtract/
We use it a lot and its a great lib.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.