简体   繁体   中英

How to add days to a current date and format in JavaScript?

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?

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));

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>

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 ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM