I am currently developing an Angular project and I am in need of obtaining the last day of a specific month for a given year using the moment library. However, I am facing some constraints. The input data does not follow a standard format like 'mm-dd-yyyy' and also the data types are set to 'any'. To solve this issue, I plan to create two input fields - one for the month and another for the year. Upon clicking the 'Get last day' button, I should be able to retrieve the last day in a numerical format for further calculations. It's a simple process:
timeselector.component.html
<input [(ngModel)]="month"/>
<input [(ngModel)]="year"/>
<button (click)="getLastDate()">Get last date</button>
<p>Last date of {{month}}/{{year}} is: </p>
Here is what I expect:
If month=12 and year=1990; then lastDate should be 31
If month=11 and year=2020; then lastDate should be 30
Special consideration must be given to leap years:
If month=2 and year=2020; then lastDate should be 29
If month=2 and year=2021; then lastDate should be 28
timeselector.component.ts
import { Component } 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
// code implementation goes here
}
}
I have tried several solutions but none seem to work for my case. I have even created a stackblitz. Any assistance would be greatly appreciated. Do you think it can be achieved using moment or do I need to write custom code? Please advise me on the correct approach.