Reputation: 4998
I'm working on an Angular project. I need last day of a given month for a given year using moment. But there are some limitations. I don't have a full date in a proper mm-dd-yyyy
, etc format. And also that data types are any
. We'll have two input fields, one for the month
and the other for year
. Then on click of Get last day
button I should get the last day in numeric format, because I've to perform some arithmetic on that later. See it's very simple:
timeselector.component.html
<input [(ngModel)]="month"/>
<input [(ngModel)]="year"/>
<button (click)="getLastDate()">Get last date</button>
<p>Last date of {{month}}/{{year}} is: </p>
And this is what I want:
If month=12, year=1990; then lastDate should be 31
If month=11, year=2020; then lastDate should be 30
Care should be taken for leap years:
If month=2, year=2020; then lastDate should be 29
If month=2, year=2021; then lastDate should be 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();
}
}
I've tried many answers but they are different from mine. I've created a stackblitz also. Please help me. Is it even doable with moment or I'll have to write some custom code of my own. Please correct me.
Upvotes: 0
Views: 518
Reputation: 115222
Get the first day of next month and then subtract 1 day from it.
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>
Upvotes: 2
Reputation: 577
Based on your demo :
moment(this.year + '-' + this.month).endOf('month').format('DD')
Upvotes: 1
Reputation: 2955
A quick solution would be this:
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>
Upvotes: 1