在我的 Angular 5项目中,我需要显示当月的最后日期。我尝试了几种技术,但没有一种能给我正确的答案。虽然JavaScript可以使用解决方案,但它在TypeScript中不起作用。
HTML:
<button class = "btn btn-sm btn-outline primary" (click) = "selectThisMonth()" >This Month</button>
<pre> Last Date of Month: {{ toDate | json }} </pre>
打字稿:
import { Component } from '@angular/core';
import {NgbDateStruct, NgbCalendar} from '@ng-bootstrap/ng-bootstrap';
const now = new Date();
@Component({
selector: 'app',
templateUrl: 'app.html'
})
export class AppComponent {
fromDate: NgbDateStruct;
toDate: NgbDateStruct;
constructor (calendar: NgbCalendar){
this.fromDate = calendar.getToday();
this.toDate = calendar.getNext(calendar.getToday(), 'd', 10);
}
selectThisMonth() {
this.toDate = {year: now.getFullYear(), month: now.getMonth+1, day: now.getDate()};
}
}
如果TypeScript中有任何可行的解决方案,请建议。
预期输出应显示&#34; 2018年4月30日&#34;因为30是当月的最后日期。
答案 0 :(得分:1)
尝试将上次日期设为
selectThisMonth() {
this.toDate = {year: now.getFullYear(), month: now.getMonth+1, day: 0};
}
我尝试过原生js
var a = new Date();
var b = new Date(a.getFullYear(), a.getMonth()+1, 0); // Mon Apr 30 2018 00:00:00 GMT+0300 (EEST)
var b = new Date(a.getFullYear(), a.getMonth()+2, 0); // Thu May 31 2018 00:00:00 GMT+0300 (EEST)
答案 1 :(得分:1)
您可以使用JS解决方案并将其粘贴到NgbDateStruct中:
selectThisMonth() {
let year = now.getFullYear();
let month = now.getMonth()+1;
let day = new Date(year, month, 0).getDate();
this.toDate = {year: year, month: month, day: day};
}