JavaScript to Display the Current Month
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
July 27, 2007 at 10:38 am
Style question, what do you think about using an Array to do the number to string conversion, like this:
function MonthAsString(m) {
return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][m];
}
It seems to be a lot more compact than the rather ponderous switch.
August 2, 2007 at 6:27 am
Yes, that is another way to do it.
May 15, 2008 at 5:21 am
OK. I have a calendar that uses the switch-case command, but now i want to create a function that will display the months ahead of time. This is what i have so far (what is in comment lines is what does not seem to work):
theDate = new Date();
var intmonth = theDate.getMonth() + 1;
function ffmonth() {
// intmonth = intmonth + 1;
}
function rwmonth() {
// intmonth = intmonth – 1;
}
myCal = new ampCalendar(intmonth, theDate.getYear());
switch ( intmonth )
{
case 1:
// la la la… (Monthly INFO goes here)
break;
case 2:
// la la la…
break;
case 3:
// la la la…
break;
// and so on…
——————————————-
The functions I have created are ffmonth() and rwmonth()…
Any Help Would Be Great!