Archive for July 26, 2007

JavaScript to Display the Current Month

Posted in JavaScript, programming on July 26, 2007 by Joey

The current month can be determined in JavaScript by using the getMonth method of the JavaScript date object, as follows:

var dteNow = new Date();
document.write(dteNow.getMonth());

The value returned by the getMonth method is an integer value between 0 and 11, with 0 being January and 11 being December. (Note that the date is determined from the client machine date.) To convert this integer to a string representation of the month, use a switch statement:

var intMonth = dteNow.getMonth();
var strMonth = '';

switch (intMonth)
{
case 0: strMonth = 'January'; break;
case 1: strMonth = 'February'; break;
case 2: strMonth = 'March'; break;
case 3: strMonth = 'April'; break;
case 4: strMonth = 'May'; break;
case 5: strMonth = 'June'; break;
case 6: strMonth = 'July'; break;
case 7: strMonth = 'August'; break;
case 8: strMonth = 'September'; break;
case 9: strMonth = 'October'; break;
case 10: strMonth = 'November'; break;
case 11: strMonth = 'December'; break;
}

document.write(strMonth);

Related articles:
JavaScript Date Object
JavaScript to Get the Day of the Week
JavaScript to Get the Current Year
JavaScript Switch Case Statement Example