【问题标题】:how do i add x number of months to current date in angular2我如何在angular2中将x个月添加到当前日期
【发布时间】:2017-11-09 11:56:07
【问题描述】:
我正在尝试在 angular2 中将 x 个月数添加到当前日期,但我发现这样做有困难,我能够以我想要的方式格式化当前日期,但它留下了添加 x到当前月份的数量。
JS
this.send_date=new Date();
this.formattedDate=new Date().toISOString().slice(0,10);
console.log(this.formattedDate);
例如,如果我距当前月份还有 5 个月,则日期应更改为 2018-04-09
【问题讨论】:
标签:
javascript
angularjs
typescript
【解决方案1】:
如果你想要这个 JS
您可以使用它:
new Date(new Date().setMonth(new Date().getMonth() + yourMonth))
对于您的情况:
new Date(new Date().setMonth(new Date().getMonth() + 5))
【解决方案2】:
在 javascript 中使用 setMonth() 方法
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);
}
}
【解决方案3】:
我建议你使用moment.js 库来做到这一点。这是一个很好的库来管理日期、日期时间和显示格式。
一个简单的例子来回答你的问题:
var date = moment(); // now
var dateIn5Months = date.add(5, 'months'); // now + 5 months
var strDate = dateIn5Months.format('YYYY-MM-dd');
结果:
更多细节在这里“moment.js doc”