Last Day of the Month w/ JavaScript
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:
var now = new Date();
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.
Tags: javascript
This entry was posted on Tuesday, November 13th, 2007 at 11:43 am and is filed under blog. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.