Month and Day Names

The JavaScript Date.getDay() and Date.getMonth() methods both return a number that is slightly different from what you would normally expect. Instead of numbering the days of the week one through seven and the months of the year one through twelve, Javascript numbers them zero through six and zero through eleven. The reason for this is that it makes it easier to convert the numbers into names.

The conversions are as simple as setting up an array of the names in your chosen language. The value returned by the appropriate method can then be used directly with the array to retrieve the corresponding name. The returned values are specifically intended for this purpose which is the reason why these values start from zero and not from one as you would expect - because arrays in JavaScript start from zero and if the values started from one then you'd either need to subtract one from them in order to do the array lookup or waste a position at the start of each array. Instead you have to add one to the returned value whenever you don't intend to use it to do the array lookup.

We can add getMonthName and getDayName methods to all our date objects making it even easier to retrieve the names. Each of these methods simply needs to define the values for the array and then return the value from the array in the position corresponding to the number returned from the corresponding method.

Date.prototype.getMonthName = function() {
var m = ['January','February','March','April','May','June','July', 'August','September','October','November','December'];
return m[this.getMonth()];
}
Date.prototype.getDayName = function() {
var d = ['Sunday','Monday','Tuesday','Wednesday', 'Thursday','Friday','Saturday'];
return d[this.getDay()];
}

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate