In the previous articles we learnt the use of JavaScript Date object to get the current Date and Time. Now you will learn to get the month of year with Month name using JavaScript Array object.
Here JavaScript Array will be used to store the names of 12 months of the year at 12 indexes of array object.
If you have no idea about JavaScript Arrays then you can learn it from the article: JavaScript Array.
JavaScript Example to get the name of the month of year using JavaScript Array:
var monthOfYear = new Array();
monthOfYear[0] = "January";
monthOfYear[1] = "February";
monthOfYear[2] = "March";
monthOfYear[3] = "April";
monthOfYear[4] = "May";
monthOfYear[5] = "June";
monthOfYear[6] = "July";
monthOfYear[7] = "August";
monthOfYear[8] = "September";
monthOfYear[9] = "October";
monthOfYear[10] = "November";
monthOfYear[11] = "December";
// Date object defined with new keyword. var myDate = new Date();
document.write("The present month is: " + monthOfYear [ myDate.getMonth() ] );
In the above example notice the array indexes from 0 to 11 starting from January to December. This sequence perfectly suits for the value returned by the JavaScript Date Object method getMonth that returns the current month where 0 stands for January, 1 for February and so on. That’s why the above sequence returns the name of the month when the getMonth returned value is passed to the monthofYear array index e.g. monthOfYear[myDate.getMonth()].
Be the first to rate this post
Tags: javascript, javascript date object, javascript month of year, javascript array, javascript date, javascript time, javascript use, javascript tutorials, learn javascript, javascript examples
10/11/2008 3:39:26 AM