How to get the last seven days, from today, (by names) in java script. like if today is Wednesday, I want to get it like (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday).
CodePudding user response:
This should order an array to follow your wished output.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date
var daysLastSeven = days.slice(d.getDay() 1).concat(days.slice(0,d.getDay() 1)).reverse()
console.log(daysLastSeven)
// output:
(7) ['Wednesday', 'Tuesday', 'Monday', 'Sunday', 'Saturday', 'Friday', 'Thursday']
CodePudding user response:
Just add the days in the string array and iterate them backward by getting current date with new Date() this will return the index of current day
const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const d = new Date();
let day = weekday[d.getDay()];
var wanteddays = 8;
var temp = d.getDay()
while(wanteddays!=0){
if (temp <0)
temp = 6;
console.log(weekday[temp]);
temp = temp-1;
wanteddays = wanteddays -1;
}
CodePudding user response:
function getDayName(date, len, local) {
let newDate = new Date(date);
let weekDays = [];
Array(len).fill(1).forEach((subDay) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}
to use:
getDayName(Date.now(), 7, 'en-EN')
OR
getDayName('10/12/2022', 7, 'en-EN')
Typescript:
function getDayName(date: Date | string | number, len: number, local:string) {
let newDate = new Date(date);
let weekDays: string[] = [];
Array(len).fill(1).forEach((subDay: number) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}