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.