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
3 Answers
Reset to default 9If 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"