0

I want to make a function that takes today's date and add more days. For example, if todays' date is 10/09/20 and I add 5 days I want to return 15/09/20.

I want to format the result as such:

15 Sep

I've created the following function:

function calcDate(days){
  var curDate = new Date();
  
  var estDate = curDate.setDate(curDate.getDate() + days);
 
  return estDate.getDate() + ' ' + estDate.getMonth();
}

However, I get the error estDate.getDate() is not a function.

If I just return estDate I also get an unformatted number, eg: 1608685587862

I've tried several approaches from Google and Stack Overflow but none work.

Would anyone know what I am to do?

Always Helping
  • 14,316
  • 4
  • 13
  • 29
MeltingDog
  • 14,310
  • 43
  • 165
  • 295

3 Answers3

1

Date.prototype.setDate returns the milliseconds of the result, which is a number, not Date object.

You can also instead add the equivalent milliseconds of those days to the current time to calculate the desired date:

function calcDate(days){
  var curDate = new Date();
  
  var estDate = new Date(curDate.getTime() + days * 24 * 60 * 60 * 1000);
 
  return estDate.toLocaleDateString('en-GB', { month: 'short', day: 'numeric' });
}

console.log(calcDate(5));
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
0

Almost there! You're using the correct date methods: .setDate(). It's just the formatting that's left. You can use Moment JS to format the date.

function calcDate(days){
  var curDate = new Date();
  
  var estDate = curDate.setDate(curDate.getDate() + days);
 
  return moment(estDate).format('DD/MM/YY');
}
console.log( calcDate( 5 ) );
console.log( calcDate( 10 ) );
console.log( calcDate( 20 ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha512-rmZcZsyhe0/MAjquhTgiUcb4d9knaFc7b5xAfju483gbEXTkeJRUMIPk6s3ySZMYUHEcjKbjLjyddGWMrNEvZg==" crossorigin="anonymous"></script>
PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

setDate() will return date value in milleseconds, you need to parse it again as date. In your example you no need to use an additional variable "estdate" you can use the "curDate" variable after you set the date.

Note: Date.getMonth() will return zerobased month i.e. for september it will return 8.

function calcDate(days){
  var curDate = new Date(); 
 curDate.setDate(curDate.getDate() + days); 
  return curDate.getDate() + ' ' + (curDate.getMonth()+1);
}
console.log(calcDate(1));

Here is the Demo (See JavaScript Tab)

Ram
  • 504
  • 3
  • 11