Finding the final day of a specific year using the moment library

When it comes to determining the last day of a year, hard-coding the date as December 31st seems like a simple solution. While there are various methods using date, js, and jquery, I am tasked with working on an Angular project which requires me to use moment for handling dates in typescript. My tech lead specifically wants me to avoid hard-coding any specific date and instead utilize a built-in method provided by moment to dynamically fetch the last day of a given year.

The issue arises when trying to implement the endOf() method with a custom year input. For example, while

const lastDayOfYear = moment().endOf('year')
works fine, attempting to do
const lastDayOfYear = moment().endOf(2025)
results in an error:

Argument of type '2025' is not assignable to parameter of type 'StartOf'

I have tried alternatives such as

const lastDayOfYear = moment().endOf("2025");
or setting a variable year=2025; followed by
const lastDayOfYear = moment().endOf(year);
, but the issue persists.

After researching the Moment docs extensively, I am unsure how to make this method work correctly. Should I consider reverting back to utilizing the Date object in JavaScript?

For instance, one option would be to create a new Date object and set it to the last day of the current year using:

new Date(new Date().getFullYear(), 11, 31);

If anyone has a solution that can provide me with the last date of a given year in MM-DD-YYYY format exclusively, please share your insights.

PS: The desired output should strictly adhere to the MM-DD-YYYY format.

Answer №1

If you are looking to calculate the end of the year using moment.js, instead of doing `12-31-${year}`, you can achieve the same result with the following code:

moment([year]).endOf('year').format('MM-DD-YYYY')

Answer №2

finding the end of a year using moment.js library:
moment(date).endOf('year');

This function will return the last date and time of the specified year for the given input Date.

Answer №3

initialize current date using new Date()

const currentDate = moment(new Date()).endOf('year');
alert(currentDate);

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

What is the best way to incorporate Ekko Lightbox into an Angular 7 Project?

I'm facing an issue while implementing Ekko lightbox in my angular project. Specifically, I want to use it in a certain component but I am unsure about how to import the necessary files into that component. After installing Ekko via NPM, I found all ...

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Is it possible to encase <v-img> within an anchor element?

I am currently using Vuetify 1.5 and have included a couple of <v-avatars></v-avatars> elements in which there is a nested <v-img></v-img>. I attempted to enclose the img tags within an a tag but encountered an issue wherein the ima ...

Enhance the JQuery dropdown by padding with zeros at the beginning for smooth incrementing

I have been attempting to customize a date dropdown in Sharepoint because the default minutes dropdown only allows selection in 5-minute intervals. Initially, I was able to make it work with the code below: $("select[id$='DateTimeFieldDateMinutes&apo ...

Utilizing the dnd library to incorporate drag and drop functionality

I've encountered an issue with the code snippet below. Although I am able to drag elements, I am unable to drop them. How can I trigger the dropFunction when a drop occurs? Drag code: <div> <a class="button" ng-class= ...

"Here's a comprehensive guide on how to connect dynamic data with angular-tree-grid components

ERROR TypeError: Cannot read property 'map' of undefined Can anyone help with binding dynamic data? I'm currently using angular-tree-grid but struggling to bind dynamic data. <html> <db-angular-tree-grid (expand)= ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...

Unable to properly call a JavaScript file from an HTML file

Executing this simple code with the JavaScript line placed under Script tags will trigger the desired alert message: <!DOCTYPE html> <!-- saved from url=(0014)about:internet --> <html> <body> <script type="text/javascript" > ...

Tips for activating AG Grid Column Auto Sizing on your website

The Issue I am experiencing difficulty in getting columns to expand to the size of their content upon grid rendering. Despite following the guidance provided in the official documentation example, and consulting sources such as Stack Overflow, I have att ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Exploring the world of React.js through the exchange and manipulation of data

Essentially, I am utilizing refs to obtain component dimensions in the componentDidMount() lifecycle method. When I log this information, I can see the width that I desire (refer to code). However, when I attempt to access and log this data in the render() ...

Is it possible to alter the page color using radio buttons and Vue.js?

How can I implement a feature to allow users to change the page color using radio buttons in Vue.js? This is what I have so far: JavaScript var theme = new Vue({ el: '#theme', data: { picked: '' } }) HTML <div ...

Mapping an object in a table only results in the final value being displayed

I am facing an issue with my data object containing an array of data that I have mapped inside a table. The problem arises when I try to retrieve the id value of any item in the table's rows using console.log(). It always returns the id of the last it ...

Creating an if statement that validates whether all variables have non-null values

I am still getting the hang of javascript and working on some coding projects from my textbooks. The current task involves creating an if statement to check if the values of the elements referenced by the names fname, lname, and zip are all not null. Here ...

Extension ConfirmButtonExtender

There is a scenario where I need to skip the ConfirmButtonExtender based on the value of another field in the page. Typically, when a user clicks on my "Cancel" button, a modal popup appears using the confirmbuttonextender and the modalpopupextender. The ...

perform an action in PHP when a button is clicked

I'm currently developing a PHP admin panel that displays a list of users in an HTML table format. Each row in the table includes a button that allows the admin to send a notification to the selected user. Below is the code I used to create and displa ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

Processing information received through an ajax.post request

I want to establish a connection with a Node.js server on localhost using ajax to send data. For testing purposes, I attempted to send text input to the server and log it there. Here is my Post-Function that triggers upon button click: function sendDat ...

Determining the parameter type of an overloaded callback: A comprehensive guide

I am currently working on creating a type-safe callback function in TypeScript with a Node.js style. My goal is to define the err parameter as an Error if it exists, or the data parameter as T if not. When I utilize the following code: export interface S ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...