最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how do i add x number of months to current date in angular2 - Stack Overflow

programmeradmin0浏览0评论

I'm trying to add x amount of months to current date in angular2 but i'm find difficulty in doing it, i'm able to get the current date formatted in a way i want but its left with adding the x amount of number to the current month.

JS

 this.send_date=new Date();
 this.formattedDate=new Date().toISOString().slice(0,10);
 console.log(this.formattedDate); 

For example if i had 5 months to the current month, the date should change to 2018-04-09

I'm trying to add x amount of months to current date in angular2 but i'm find difficulty in doing it, i'm able to get the current date formatted in a way i want but its left with adding the x amount of number to the current month.

JS

 this.send_date=new Date();
 this.formattedDate=new Date().toISOString().slice(0,10);
 console.log(this.formattedDate); 

For example if i had 5 months to the current month, the date should change to 2018-04-09

Share Improve this question asked Nov 9, 2017 at 11:56 user6579134user6579134 8393 gold badges12 silver badges36 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

If you want this by JS

You can use that: new Date(new Date().setMonth(new Date().getMonth() + yourMonth))

for your case: new Date(new Date().setMonth(new Date().getMonth() + 5))

Use setMonth() method in javascript

export class AppComponent  {
  name = 'Angular 5';
   send_date=new Date();
   formattedDate : any;
   constructor(){
     this.send_date.setMonth(this.send_date.getMonth()+8);
     this.formattedDate=this.send_date.toISOString().slice(0,10);
 console.log(this.formattedDate); 
   }

}

I suggest you tu use moment.js library to do that. It's a good library to manage date, dateTime and format to display.

An quick example to answer your problem :

var date = moment(); // now
var dateIn5Months = date.add(5, 'months'); // now + 5 months
var strDate = dateIn5Months.format('YYYY-MM-dd');

And the result :

More details here "moment.js doc"

发布评论

评论列表(0)

  1. 暂无评论