0

I'm new to javascript, i'm trying to make a function to every time that a date is Saturday/Sunday, it will return 'weekend' instead of the day...

The current function (i === 6) is returning the 6th day of each month.

function weekend(i) {
  if (i === 6 || i === 0) {
    i = "weekend";
  }
  return i;
}

let d = new Date();
weekend(d.setDate(d.getDate() + 5));
let n = weekend(d.getDate());
let m = d.getMonth() + 1;
let o = d.getFullYear();
let dateOp = n + "/" + m + "/" + o;
dateOp;
console.log(dateOp); // output 24/1/2021
// expected output weekend/1/2021

Fixed code ([red])

const weekend = d => d.getDay()%6==0 ? "weekend" : d.getDate(); 
// let d = new Date(); // uncomment when tested
let d = new Date(2021,0,19,15,0,0,0); // 19/01/2021 @ 15:00  - remove when tested
d.setDate(d.getDate() + 5); // 5 days from now
let n = weekend(d);
let m = d.getMonth() + 1;
let o = d.getFullYear();
let dateOp = n + "/" + m + "/" + o;
console.log(dateOp); // output weekend/1/2021
mplungjan
  • 169,008
  • 28
  • 173
  • 236
M. M.
  • 11
  • 3
  • getDay() will give you the day of the week. Tuesday (that's today) will give you 2 as result. With that in mind you can achieve what you're trying to do. – 1x2x3x4x Jan 19 '21 at 11:32
  • `const weekend = d => d.getDay()%6==0 ? "weekend" : d.getDate();` usage: `let n = weekend(d);` – mplungjan Jan 19 '21 at 11:53
  • `weekend(d.setDate(d.getDate() + 5));` is not the correct way to advance the date. Also `dateOp;` on its own does nothing. See the updated code in your question. – mplungjan Jan 19 '21 at 11:58
  • The return value of `weekend(d.setDate(d.getDate()+5))` is not used. *setDate* returns the time value of the updated Date, which is currently about 1611061491038. The call does change *d* though. In the next call you're passing the date, i.e. the day of the month, not the day of the week. So use `let n = weekend(d.getDay())` instead. – RobG Jan 19 '21 at 13:06

1 Answers1

0

this function would be work. I add comments in code

function getDateString (myDate) {
  const year = myDate.getFullYear()
  const month = myDate.getMonth() + 1
  let date = myDate.getDate()
  // 0 is sunday, 6 is saturday
  // change weekend if is 0 or 6
  if ([0, 6].includes(myDate.getDay())) date = 'weekend'
  const str = `${date}/${month}/${year}`
  return str
}

console.log(getDateString(new Date()))
console.log(getDateString(new Date('2021/01/17')))
Jun
  • 216
  • 1
  • 13