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\");
Try:
var objDate = new Date("10/11/2009");
var strDate =
objDate.toLocaleString("en", { day: "numeric" }) + ' ' +
objDate.toLocaleString("en", { month: "long" }) + ' ' +
objDate.toLocaleString("en", { year: "numeric"});
Shorter version:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const d = new Date();
document.write("The current month is " + monthNames[d.getMonth()]);
Note (2019-03-08) - This answer by me which I originally wrote in 2009 is outdated. See David Storey's answer for a better solution.
If you don't mind extending the Date prototype (and there are some good reasons to not want to do this), you can actually come up with a very easy method:
Date.prototype.monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
Date.prototype.getMonthName = function() {
return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
return this.getMonthName().substr(0, 3);
};
// usage:
var d = new Date();
alert(d.getMonthName()); // "October"
alert(d.getShortMonthName()); // "Oct"
These functions will then apply to all javascript Date objects.
You can handle with or without translating to the local language
const objDate = new Date("10/11/2009");
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
if (objDate !== 'Invalid Date' && !isNaN(objDate)) {
console.log(objDate.getDate() + ' ' + months[objDate.getMonth()] + ' ' + objDate.getFullYear())
}
const convertDate = new Date('10/11/2009')
const lang = 'fr' // de, es, ch
if (convertDate !== 'Invalid Date' && !isNaN(convertDate)) {
console.log(convertDate.getDate() + ' ' + convertDate.toLocaleString(lang, {
month: 'long'
}))
}
document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))
I heartily recommend the format function from, the moment.js library, which you can use like this:
moment().format("MMM"); // "Apr" - current date
moment(new Date(2012, 01, 04)).format("MMM"); // "Feb" - from a local date
moment.utc(new Date(2012, 00, 04).format("MMM"); // "Jan" - from a UTC date
Use "MMMM" instead of "MMM" if you need the full name of the month
In addition to a lengthy list of other features, it has strong support for internationalization.