gpt4 book ai didi

javascript - 在 JavaScript 函数上获取周五停止的日期

转载 作者:行者123 更新时间:2023-12-01 04:03:57 25 4
gpt4 key购买 nike

如何让我的代码只显示周五之前的日期,它目前显示周六之前的日期:

var dayString = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

var now = new Date();
var currentDay = now.getDay(); // return 0 for Sunday, 6 for Saturday
var result = [];
var tempDate = new Date(now.getTime());
tempDate.setDate(now.getDate() - (currentDay + 6) % 7); // now tempDate is previous Monday
while (tempDate.getDay() != 0) {
var currentMonth = tempDate.getMonth() + 1;
if (currentMonth < 10) currentMonth = "0" + currentMonth;
result.push([tempDate.getDay() - 1, tempDate.getDate() + "-" + currentMonth + "-" + tempDate.getFullYear(), dayString[tempDate.getDay()]]);
tempDate.setDate(tempDate.getDate() + 1);
}
console.log(result);

https://jsfiddle.net/xut9tkpz/

最佳答案

如果您想获取下周五之前的日期,请使用以下命令:

var now = new Date();
var results = [];
while(now.getDay() !== 5) {
results.push(new Date(now)); // push Date Object to results;
now.setDate(now.getDate() + 1);
}

如果您想获取上周五之前的日期:

var now = new Date();
var results = [];
while(now.getDay() !== 5) {
results.push(new Date(now)); // push Date Object to results;
now.setDate(now.getDate() - 1);
}

如果您想获取过去 1 周内直到上周五的日期:

var now = new Date();
now.setDate(now.getDate() - 7);
var results = [];
while(now.getDay() !== 5) {
results.push(new Date(now)); // push Date Object to results;
now.setDate(now.getDate() + 1);
}

如果您想将星期五包含在结果对象中,只需将 5 更改为 6

关于javascript - 在 JavaScript 函数上获取周五停止的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41970722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com