gpt4 book ai didi

javascript - 提前 5 个工作日

转载 作者:行者123 更新时间:2023-11-30 14:34:10 28 4
gpt4 key购买 nike

我需要获取从当天算起的 5 个工作日的数组。

今天是:06/04/2018

我需要的输出是:

{
0: 06/01/2018, //fri.
1: 05/31/2018, //thur.
2: 05/30/2018, //wed.
3: 05/29/2018, //tue.
4: 05/28/2018 //mon.
};

这是我的代码和当前输出:

{
0: business_day_from_date(1),//sun. i don't want weekends
1: business_day_from_date(2),//sat i don't want weekends
2: business_day_from_date(3),//fri.
3: business_day_from_date(4),//thur.
4: business_day_from_date(5),//wed.
}


function business_day_from_date(daysAgo){
var date = new Date();
date.setDate(date.getDate() - daysAgo);
return date.getMonth() + "-" + date.getDate() + "-" + date.getFullYear();
}

工作日是:

  • 星期一
  • 星期二
  • 星期三
  • 星期四
  • 星期五

最佳答案

以下应该有效:

function business_day_from_date(daysAgo, date) {//pass date in
const result = [];
const d = new Date(date);//do not mutate date passed in
while (daysAgo > 0) {//while we have not enough work days
d.setDate(d.getDate() - 1);//take one day of the copy of the date passed in
if (d.getDay() !== 0 && d.getDay() !== 6) {//if not sat or sun
daysAgo--;//we found one
result.push(new Date(d));//add copy of the found one to result
}
}
return result.reverse();//oldest to newest
}
function formatDate(date){
return (date.getMonth()+1) + "-" + date.getDate() + "-" + date.getFullYear()
}
console.log(
"date passed in:",formatDate(new Date()),
business_day_from_date(3, new Date()).map(
function(date){return formatDate(date);}
)
)

使用 daysAgo 从传入的日期返回天数并获取所有工作日,但不包括传入的日期。

function business_day_from_date(daysAgo, date) {//pass date in
const result = [];
const d = new Date(date);//do not mutate date passed in
const end = new Date(d);
d.setDate(d.getDate()-daysAgo);//go back the daysAgo value
while (d.getTime()<end.getTime()) {//while we have not passed date passed in
if (d.getDay() !== 0 && d.getDay() !== 6) {//if not sat or sun
daysAgo--;//we found one
result.push(new Date(d));//add copy of the found one to result
}
d.setDate(d.getDate() + 1);//add a day
}
return result;//oldest to newest, use .reverse to get newest to oldest
}
function formatDate(date){
return (date.getMonth()+1) + "-" + date.getDate() + "-" + date.getFullYear()
}
console.log(
"date passed in:",formatDate(new Date()),
business_day_from_date(3, new Date()).map(
function(date){return formatDate(date);}
)
)

关于javascript - 提前 5 个工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686060/

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