【问题标题】:Angular & TypeScript - Displaying the Last Date of the Current MonthAngular 和 TypeScript - 显示当月的最后日期
【发布时间】:2018-04-13 11:56:50
【问题描述】:

在我的 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


    【解决方案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};
    }
    

    【讨论】:

      【解决方案2】:

      尝试将最后日期设置为

      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)
      

      【讨论】:

      • 另外,我如何区分是四月还是五月
      • 从当前日期的月份开始
      • 为此,我们将使用 if..else... 但是有什么方法可以使用内置函数来找出当月的最后一个日期...就像有内置方法来查找当前日期、月份等
      • 我建议的方法是设置下个月没有一天 - var b = new Date(new Date().getFullYear(), new Date().getMonth()+1)。它应该返回一个月的第一天。在您的情况下,尝试另外将 day 设置为 -1 -> var b = new Date(new Date().getFullYear(), new Date().getMonth()+1, -1) 也许它会有所帮助
      • 使用 5 角日期管道显示您的日期。 angular.io/api/common/DatePipe
      猜你喜欢
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      相关资源
      最近更新 更多