andrew_kincaid
ServiceNow Employee
ServiceNow Employee

Lately, I've found myself searching the World Wide Web - isn't that just fun to say? - for common JavaScript solutions for basic tasks like getting the number of days in a month. The common solutions out there don't necessarily work as expected in the Mozilla Rhino (server-side) environment. My new mission is to find those solutions and translate them into solutions that work in ServiceNow - ideally in both server and client-side code.

Here is my solution for getting the number of days in a month:


function daysInMonth(year, month) {
var d = new Date(year, month + 1, 1);
d.setDate(d.getDate() - 1);
return d.getDate();
}


The usual solution involves setting the "day" argument of the


new Date(year, month, day)
constructor to zero to get the last day of the previous month and shifting the months to one-based numbering (1=Jan) so you have to think 1=Jan and the function thinks 1=Feb.

Come to find out, Rhino does not have the '0th day' side-effect. When you create a

new Date(2013,2,0)
in Rhino using the '0th day', it rounds up and you get the first day of the month - not the intended last day of the previous (or current) month. Confusing, right?

Here is the same solution above with comments and examples:


// Uses zero-based month numbers (0=Jan, 1=Feb) to be consistent with other JavaScript functions
function daysInMonth(year, month) {

// Create a new Date for the first day of the *next* month
var d = new Date(year, month + 1, 1);

// Subtract one day to get the last day of the *current* month
d.setDate(d.getDate() - 1);

// Return the number of the last day of the *current* month
return d.getDate();
}

// Server example:
gs.print( daysInMonth(2013,4) ); // May (4) 2013 = 30 days

// Client example
alert( daysInMonth(2013,4) ); // May (4) 2013 = 30 days


By using the "first day of the next month and subtract one day" logic, this function works in both server and client-side code.

UPDATE: I want to point out that when you supply the last month of the year (11=Dec), the function uses a month number of 12, which falls outside of the range 0=Jan to 11=Dec, but that's ok - it will return a date for January of the next year. That's why this function works for the month of December and you don't have to adjust for it. While Rhino might not understand the 0th day of the month, it does understand the 13th month of the year 😉

3 Comments