Part of the Date object, the getMonth() method returns the current month, based on the client computer's date/time settings; months are zero-based in JavaScript: January is 0, and December is month 11. Just make sure to remember it - we'll explain an upside of this approach. var cal = new Date(); // Automatically set to current date/time alert( cal.getMonth() );
The downside of starting zero is its counter-intuitiveness - but this plays well with arrays, which also start their position index at zero. Let's get the current month's name, using an array: // Create an array of months, with January at zero (first element) var mos = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; var cal = new Date(); alert( mos[ cal.getMonth() ] );
You can use an anonymous date object (vs. creating variable) to directly get the month: alert( (new Date()).getMonth() );
To get two-digit months, use a modified function from "Add zero in front of numbers", using parseInt() as precaution and automatically adding 1 to show months in human-friendly format! function twoDigitMonth( mo ) { mo = parseInt( mo ) + 1; // Add 1 to current month return ( mo.toString().length < 2 ? "0"+mo : mo ).toString(); }
// Returns '01' for January, '02' for February, etc. alert( twoDigitMonth( (new Date()).getMonth() ) );
The PHP equivalent to JavaScript's getMonth() method is the date() function - its output depends on the character(s) passed as argument - below are the 4 for the (current, by default) month: echo date('n') . '<br>'; // 1 ... 12 echo date('m') . '<br>'; // 01 ... 12 (automatic zero padding) echo date('M') . '<br>'; // Jan ... Dec (use strtoupper() to capitalize) echo date('F') . '<br>'; // January ... December