如何获得给定年份的给定月份的最后一天

时间:2020-04-06 18:58:36

标签: angular typescript momentjs

我正在做一个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>

这就是我想要的:

如果month = 12,year = 1990;那么lastDate应该是31

如果month = 11,year = 2020;那么lastDate应该是30

应注意leap年:

如果month = 2,year = 2020;那么lastDate应该是29

如果month = 2,year = 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。请帮我。它甚至可以实现,还是我必须编写一些自己的自定义代码。请纠正我。

3 个答案:

答案 0 :(得分:2)

获取下个月的第一天,然后再subtract 1天。

let month = 2,
  year = 2020,
  lastDate = "";

var now = moment(`${month}/1/${year}`).add(1,'months').subtract(1, 'days');

alert(now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

答案 1 :(得分:1)

一个快速的解决方案是:

const getLastDay = (year, month) => moment().year(year).month(month - 1).daysInMonth();

console.log(getLastDay(2020, 2));
console.log(getLastDay(2021, 2));
console.log(getLastDay(1990, 12));
console.log(getLastDay(2020, 11));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

答案 2 :(得分:1)

根据您的演示:

moment(this.year + '-' + this.month).endOf('month').format('DD')