Angular 和 TypeScript - 显示当前月份的最后日期

问题描述 投票:0回答:3

在我的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 中有任何可行的解决方案,请提出建议。

预期输出应显示“2018 年 4 月 30 日”,因为 30 是当月的最后日期。

angular typescript datepicker angular5
3个回答
4
投票

您可以使用 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};
}

3
投票

尝试将最后日期设置为

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)

0
投票
const firstDay = new NgbDate(today.year, today.month, 1); //First day of the current month

//Last day of the current month
const lastDay = this.calendar.getPrev(this.calendar.getNext(firstDay, 'm', 1), 'd', 1);

console.log('First day of the current month: ', firstDay);
console.log('Last day of the current month: ', lastDay);
© www.soinside.com 2019 - 2024. All rights reserved.