JavaScript last day of the month

I usually don’t do post about simple JavaScript issues, but I figured I might need this solution again and might as well write it down.

I am working on a new product called Archibus Web Central. Basically it is a building inventory management tool. The application is made up of an XML and JavaScript Hybrid code. Poor explanation, but not really important to this post.

In the project I am working on, I need to determine a start and end date in order to get a range of dates. To make my life simple, I am just using a set of drop lists with months and years as options. After the start and end values are collected, I want to set the date range to the 1st day of the month for the start selection and the last day of the month for the end selection.

i.e. August 2014 gives me 08/01/2014 if it is the start and 08/31/2014 if it is the end.

Well, since JavaScript doesn’t have a LastDay() function, I need to calculate what is the last day. And, since months are different and leap year and such, I can’t simply just put 30 as the Day in the Date object. The key is to get the next month and subtract from there.


//get the drop lists and the selected values

var eYear = document.getElementById('endYearList');

var eYearValue = eYear.options[eYear.selectedIndex].value;

var eMonth = document.getElementById('endMonthList');

var eMonthValue = eMonth.options[eMonth.selectedIndex].value;

//create the Date object

var endDate = new Date(eYearValue,eMonthValue ,1,0,0,0,0);

//create the Date object that will provide the Day value

var endDateDate = new Date(endDate).setMonth() + 1);

//set the Day with the endDateDate

endDate.setDate(new Date(endDateDate - 1).getDate)):

It might not be the smallest or best code, but at least I know that it provides the correct value.

About DeanLogic Passport
Dean has been playing around with programming ever since his family got an IBM PC back in the early 80's. Things have changed since BASICA and Dean has dabbled in HTML, JavaScript, Action Script, Flex, Flash, PHP, C#, C++, J2ME and SQL. On this site Dean likes to share his adventures in coding. And since programming isn't enough of a time killer, Dean has also picked up the hobby of short film creation. This is my Passport account (formerly my Z30 account) . Any posts made by this account were created Working Wide with my BlackBerry Passport device.

About DeanLogic Passport

Dean has been playing around with programming ever since his family got an IBM PC back in the early 80's. Things have changed since BASICA and Dean has dabbled in HTML, JavaScript, Action Script, Flex, Flash, PHP, C#, C++, J2ME and SQL. On this site Dean likes to share his adventures in coding. And since programming isn't enough of a time killer, Dean has also picked up the hobby of short film creation. This is my Passport account (formerly my Z30 account) . Any posts made by this account were created Working Wide with my BlackBerry Passport device.