【发布时间】:2020-04-06 18:58:36
【问题描述】:
我正在做一个 Angular 项目。我需要使用时刻给定年份的给定月份的最后一天。但是有一些限制。我没有正确的mm-dd-yyyy 等格式的完整日期。而且数据类型是any。我们将有两个输入字段,一个用于month,另一个用于year。然后单击Get last day 按钮,我应该得到数字格式的最后一天,因为稍后我必须对其执行一些算术运算。看很简单:
timeselector.component.html
<input [(ngModel)]="month"/>
<input [(ngModel)]="year"/>
<button (click)="getLastDate()">Get last date</button>
<p>Last date of {{month}}/{{year}} is: </p>
这就是我想要的:
如果月=12,年=1990;那么 lastDate 应该是 31
如果月=11,年=2020;那么 lastDate 应该是 30
应注意闰年:
如果月=2,年=2020;那么 lastDate 应该是 29
如果月=2,年=2021;那么 lastDate 应该是 28
timeselector.component.ts
import { Component, DoCheck, OnInit } from '@angular/core';
import moment from 'moment';
@Component({
selector: 'app-timeselector',
templateUrl: './timeselector.component.html',
styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent {
month=12;
year=1990;
lastDate="";
getLastDate() {
// logic to get last date of the given month NOT WORKING
// const fromDate = moment(this.month, 'MM-DD-YYYY', true);
// const toDate = moment(this.year, 'MM-DD-YYYY', true);
// const customStartMonth = moment(fromDate, 'MM-DD-YYYY').month();
// const customStartYear = moment(fromDate).year();
// const customendMonth = moment(toDate, 'MM-DD-YYYY').month();
// const customendYear = moment(toDate).year();
}
}
我尝试了很多答案,但它们与我的不同。我还创建了一个stackblitz。请帮我。是否可以立即使用,或者我将不得不编写一些自己的自定义代码。请纠正我。
【问题讨论】:
标签: angular typescript momentjs