Get 5 business days before today

时间:2018-06-04 17:43:10

标签: javascript

I need to get an array of 5 business days from the current day.

Today is: 06/04/2018

The output i need is:

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

This is my code and current output:

{
     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();
}

Business days are:

  • monday
  • tuesday
  • wednesday
  • thursday
  • friday

2 个答案:

答案 0 :(得分:2)

以下内容应该有效:



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);}
  )
)
&#13;
&#13;
&#13;

答案 1 :(得分:0)

放手一搏:

str_extract(df2$Description, paste(toupper(keywords2), collapse="|"))
#[1] "MOTOR"    "BOMBA"    "CARTUCHO" "FILTRO"   "MOLDE"    "BOMBA"    "MOLDE"   
#[8] "FILTRO"   "BOMBA"