Reputation: 3788
I'm trying to figure out, how to create a javascript array of names of ie. last 7 days starting from today.
I know getDay() will return a number of the day, which I can then use as an index to access an element of an array containing days of the week.
This will give me the name of today, but I need to go back chronologically to create an array of last few days I couldn't find anything similar to this problem on web.
Any elegant solution for this? jQuery perhaps?
Upvotes: 3
Views: 5675
Reputation: 5712
const days = ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saterday', 'sunday'];
var goBackDays = 7;
var today = new Date();
var daysSorted = [];
for(var i = 0; i < goBackDays; i++) {
var newDate = new Date(today.setDate(today.getDate() - 1));
daysSorted.push(days[newDate.getDay()]);
}
alert(daysSorted);
Upvotes: 7
Reputation: 607
Maybe not the most elegant way:
var numdays = 7; // Change it to the number of days you need
var d = new Date();
var n = d.getDay();
var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var myArray = new Array(numdays);
for(var i=0;i<numdays;i++){
myArray[i]=weekday[(n-i+numdays)%7];
}
console.log(myArray); // Result: ["Thursday", "Wednesday", "Tuesday", "Monday", "Sunday", "Saturday", "Friday"]
Upvotes: 0
Reputation: 1033
function myFunction(day) {
var weekday =["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
return weekday[day];
}
var currentDate = new Date().getDay();
var week=[0,1,2,3,4,5,6];
var a=week.splice(currentDate);
var loopWeek=a.concat(week);
var freshWeek=[];
for(var i=0;i<loopWeek.length;i++){
freshWeek.push(myFunction(loopWeek[i]))
}
console.log(freshWeek);
Upvotes: 1