mdesjardins.github.io

I recently had to calculate the last day of the month using JavaScript. When I Google’d for a way to do this (I had an idea for a solution already, but I wanted to look online first), I was pretty surprised by how much work some of the proposed solutions were, like this and (even worse) this. One trick I learned from SQL programming is that it doesn’t need to be that complicated. All you need to do is jump to the next month, go to the first day of that month, then subtract one day. Here’s the code:

now.setMonth(now.getMonth() + 1); // rounds back to January if needed (e.g., 13th month).
now.setDate(0)  // now is now set to the last day of the previous month,
                // i.e., the "zeroth" day of the current month = the last day of the previous month.