Skip to content
Advertisement

function nextWeek(date) in JavaScript

i am doing a javascript assessment concerning the class Date Here is the assessment: “Write the body of the nextWeek(date) function that returns a date 7 days after the date given in inputdate is always a defined Date object.

So i wrote that code below:

function nextWeek(date){
var today=new Date();
var nextweek=new Date(today.getFullYear(),today.getMonth(),today.getDate()+7);
return nextweek;
}
var d=new Date();
console.log(d);
console.log(nextWeek(d));

And the result is :

“2021-04-25T15:02:16.234Z”

“2021-05-01T22:00:00.000Z”

for me it is correct because there is one week(7 days) long between “2021-04-25T15:02:16.234Z” and “2021-05-01T22:00:00.000Z”

But they told me that my code is wrong,i don’t know what is wrong with it, Do you have any idea of what’s wrong in that code above?

Advertisement

Answer

function nextWeek(date){
  var today=new Date(); // Remove this
  var nextweek=new Date(today.getFullYear(),today.getMonth(),today.getDate()+7); // Change today -> date
  return nextweek;
}
var d=new Date();
console.log(d);
console.log(nextWeek(d)); 

// Simple way of doing it.
function nextWeek(date) {
  date.setDate(date.getDate() + 7);
  return date;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement