-1

I have a strange requirement where I need a find the date based on given number and type = before/after parameter

i.e., for example

Date = new Date() - 3/8/2020 (It can be any date)
type = before
days = 7(It can be any number)

Now I need to find the date excluding the weekends.

In this case it would be 23/7/2020 .Because 2/8,1/8,26/7,25/7 are weekends, so those should be excluded and calculated.

Simillarly if type = after , date will be 12/8/2020 .In this case 8/8 and 9/8 are weekends and those will be excluded.

So how can we implement this as function that takes date,days,type as parameters and return the date.

i.e.,

function calculateDate(day,days,type){
  /* Some logic 
     if(new Date(day).getDay() !== 6||7){};
  */
 return date
}

Note : I cant use any libraries like moment/dayjs etc as I have restrictions with the development tool Im using..I need to implement in pure javascript logic

Can any javascript datetime expert help me on this as I couldn't crack this.

Thanks in advance

user7350714
  • 365
  • 1
  • 6
  • 20
  • Are you trying to say you want the last weekday? or is it minus x number of working days? – Liam Aug 03 '20 at 10:31
  • I'd use the dayjs library for this. – Josh Wulf Aug 03 '20 at 10:31
  • Or [moment](https://momentjs.com/) – Liam Aug 03 '20 at 10:32
  • @Liam not exactly I need the date which is 7 days before excluding the weekends – user7350714 Aug 03 '20 at 10:32
  • right so minus x number of working days then.. – Liam Aug 03 '20 at 10:33
  • 1
    @JoshWulf I cant use any libraries as there are restrictions with the tool Im using – user7350714 Aug 03 '20 at 10:33
  • Have a look at [this then](https://stackoverflow.com/questions/6499944/add-subtract-business-days-in-javascript). There are multiple solutions to this problem if you google a bit – Liam Aug 03 '20 at 10:36
  • @Liam here I have given 7 just as an example..It can be any number – user7350714 Aug 03 '20 at 10:37
  • There are many questions and answers already about [adding and subtracting business days](https://stackoverflow.com/search?q=%5Bjavascript%5D+add+business+days). Write some code, then ask if you have problems. Simply asking for code is not a suitable question here. – RobG Aug 04 '20 at 05:36

1 Answers1

2
const date = new Date()
let days = 7 // Adjust accordingly
let delta = -1 // Set +1 to check 'days after' instead of 'days before'

while (days > 0) {
  // Remove a day
  date = date.setDate(date.getDate() + delta) 
  // Check if weekend (adjust your days number according to your needs)
  const isWeekend = date.getDay() === 6 || date.getDay() === 0
  // If it is not a weekend, reduce the number of days to subtract
  if (!isWeekend) {
    days = days - 1
  }
}

return date
gbalduzzi
  • 9,356
  • 28
  • 58