How can I generate the name of the month (e.g: Oct/October) from this date object in JavaScript?
var objDate = new Date(\"10/11/2009\");
It can be done as follows too:
var x = new Date().toString().split(' ')[1]; // "Jul"
You could just simply use Date.toLocaleDateString() and parse the date wanted as parameter
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
const options = { year: 'numeric', month: 'short', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012
console.log(event.toLocaleDateString('en-US', options));
// US format
// In case you only want the month
console.log(event.toLocaleDateString(undefined, { month: 'short'}));
console.log(event.toLocaleDateString(undefined, { month: 'long'}));
You can find more information in the Firefox documentation
Store the names in a array and look up by the index of the month.
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
document.write("The current month is " + month[d.getMonth()]);
JavaScript getMonth() Method
Just extending on the many other excellent answers - if you are using jQuery - you could just do something like
$.fn.getMonthName = function(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
return monthNames[date.getMonth()];
};
where date
is equal to the var d = new Date(somevalue)
. The primary advantage of this is per @nickf said about avoiding the global namespace.
Date.prototype.getMonthName = function() {
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
return monthNames[this.getMonth()];
}
It can be used as
var month_Name = new Date().getMonthName();
Tested on IE 11, Chrome, Firefox
const dt = new Date();
const locale = navigator.languages != undefined ? navigator.languages[0] : navigator.language;
const fullMonth = dt.toLocaleDateString(locale, {month: 'long'});
console.log(fullMonth);