Discovering the final day of a specified month within a particular year using MomentJS

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.

Answer №1

Calculate the start date of the following month and then deduct 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>

Answer №2

After reviewing your demonstration:

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

Answer №3

One way to quickly solve this problem is using the following code snippet:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming a plain text field into an input field upon clicking a button or icon using Angular/Typescript

I am a beginner with Angular 6 and I'm trying to implement functionality where clicking a button or icon will change a text field into an input field. See the snippet of code and expected output below. Thank you in advance. <div> <mat-for ...

The animation in ThreeJs encounters context issues within Angular 2

I am trying to incorporate ThreeJs into my Angular 2 project. I have successfully rendered a scene with a simple cube, but I ran into an issue when using the animate() function. Here is the code snippet: import { OnInit, Component } from '@angular/co ...

Is there a way to combine two arrays of objects that may be undefined?

Here is the object I am working with: interface Cart { orderPromo?: ProductPromotion[], productPromo?: ProductPromotion[], } Both properties are of the same type, but they can be undefined. What is the most efficient and clean way to merge them? ...

Karma-coverage examines the test coverage of JavaScript files rather than TypeScript files within Angular 2

I am facing an issue with checking test coverage in TypeScript files using Istanbul and setting test thresholds via karma-coverage. The problem arises because karma-coverage checks test coverage in JavaScript files instead of TypeScript, which leads to mis ...

The power of Storybook and NX combined: One central Storybook instance to rule them all projects

I am managing a collection of 7 angular apps within an nx monorepo, each utilizing visual components stored in a shared-ui lib. My goal is to set up a new project with Storybook where I can automatically generate stories for all these visual components. Th ...

Looking for a solution to the error message: "X is not able to be assigned to the type 'IntrinsicAttributes & Props'"

Greetings everyone! I need some assistance in setting up single sign-on authentication using React, Azure AD, and TypeScript. I'm encountering a type error in my render file and I'm unsure of how to resolve it. Below is the specific error message ...

assigning state to a React component by utilizing onClick event in a functional component with TypeScript

const Navigation = () => { const [activeItem, setActiveItem] = useState<string>("tasks"); return { <NavigationContainer> <NavItem onClick=(() => setActiveItem("settings")/> ...

The CSS3D object stands out among 3D objects, maintaining its visibility even as the scene is rotated

I'm utilizing the CSS3DRenderer to render HTML on FBX 3D objects. Everything seems to be working well, except that when I rotate my scene, the HTML becomes visible through the 3D objects as if they were transparent. I am relatively new to Three.js and ...

The data retrieved from Firebase is coming back as not defined

I am currently working on an Angular component that is designed to showcase data retrieved from Firebase in a table using a service: <table class="table table-sm"> <thead> <th>Animal Name</th> <th>Species</th> ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Error occurred when attempting to link user services with report controller

Greetings, I am currently working on a Nest Js mini project that consists of two separate modules: reports and users. Each module has its own Service, controller, and repositories. The reports module has a many-to-one relation with the users module. My g ...

Discovering the IMEI number with Ionic4 and Angular

Recently, I started working with the Ionic framework and I'm trying to find a way to uniquely identify each device. My initial thought was to obtain the IMEI number, but I'm unsure of how to do that. I attempted to use Ionic4 with Angular cordova ...

Tips on including text within PrimeNG speeddial option buttons?

Instead of icons, I would like to have text displayed in the options of my speed dial component. https://i.sstatic.net/I4Rx5.png This is what I am aiming for https://i.sstatic.net/0u5OP.png Thank you in advance ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

Testing Angular components with different parameters

Currently, I am in the process of testing a method that requires an id parameter to delete an object. The test case is as follows: it('should delete the car object for the given ID', () => { const mockId = '1'; const carObj ...

Troubleshooting: Issue with Angular routerlink not functioning in the sidebar section of SB Admin 2 Bootstrap 4 template

I am currently in the process of integrating the SB Admin2 template with my Angular 7 project. Unfortunately, I have encountered an issue where the links in the sidebar are unresponsive and not clickable at all. However, when I place a router link within t ...

What is the reason behind the narrowing of the type by indexing into a mapped type?

This question is inspired by an amazing answer found here: My curiosity lies in why the indexing works in the mapped type trick. Let's illustrate with an example: type MyData = { a: { alpha: string; }; b: { beta: number; } } type ...

What is the best way to establish communication with the root component in Angular?

I have implemented a modal in the root component that can be triggered from anywhere. However, I am facing a dilemma on how the bottom component can communicate with the top component without excessive use of callback functions. Root Component <contai ...

Tips for managing a group of checkboxes in Angular 2 RC5

My task involves creating a form where users can edit their magazine subscriptions. Here is the code snippet I am working with: Component: export class OrderFormComponent { subscriptions = [ {id: 'weekly', display: 'Weekly new ...

Retrieving the ngModel value in Ionic without triggering any actions

After trying to send the value of <ion-text> to a TypeScript file when a button is clicked on the same HTML page, I encountered an issue where it didn't work as expected. <ion-text [(ngModel)]='xy' ngDefaultControl >'vari ...