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?
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?
Share Improve this question asked Nov 27, 2014 at 14:42 robjezrobjez 3,7883 gold badges34 silver badges37 bronze badges 5- you mean like ['thursday', 'wednesday', ..., 'friday'] ? – Mivaweb Commented Nov 27, 2014 at 14:44
- Which language would you want the day names in? – Rory McCrossan Commented Nov 27, 2014 at 14:45
- @Rory McCrossan - whatever, but can be English for start – robjez Commented Nov 27, 2014 at 14:46
- Have a look at this: stackoverflow./questions/9501596/… – twain Commented Nov 27, 2014 at 14:55
- @twain - this is not very useful to me mate – robjez Commented Nov 27, 2014 at 15:26
3 Answers
Reset to default 7
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);
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);
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"]