To get the date for the last day of the current month in JavaScript, you can use the Date
constructor along with some basic arithmetic. Alternatively, if you are willing to use a third-party library, you can use moment.js
to make this easier.
Here's an example using the Date
constructor:
index.tsx171 chars6 lines
This works by first getting the current year and month using the Date
constructor. We then construct a new Date
object with the year and month, but a day of 0 which means the last day of the previous month. Since we want the last day of the current month, this will give us the correct date.
Here's the same example using moment.js
:
index.tsx77 chars3 lines
This is much simpler and more concise, and works by using the moment()
function to create a new moment.js
object representing the current date and time. We then call the endOf('month')
method to get the last day of the current month.
gistlibby LogSnag