通过名称javascript获取最后7天



如何用java脚本(按名称(获得从今天起的最后七天。如果今天是星期三,我想把它变成(星期三、星期二、星期一、星期日、星期六、星期五、星期四、星期三(。

只需在字符串数组中添加天数,并通过new date((获取当前日期来向后迭代它们这将返回当前日期的索引

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;
}

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;
}

使用:

getDayName(Date.now(), 7, 'en-EN') 
OR
getDayName('10/12/2022', 7, 'en-EN')

打字:

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;
}

这应该按照您想要的输出对数组进行排序。

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var currentDay = days[ (new Date()).getDay()]
days =  days.reverse();
var x = days.indexOf(currentDay)
var daysLastSeven =  days.slice(x).concat(days.slice(0,x))
console.log(daysLastSeven)

相关内容

  • 没有找到相关文章

最新更新