I want to get the name of the month in JavaScript in capitals.
I know I can use the getMonth()
method to get the current month and use the number to extract the month name in capitals from an array, but is there a built-in method to do the same?
I want to get the name of the month in JavaScript in capitals.
I know I can use the getMonth()
method to get the current month and use the number to extract the month name in capitals from an array, but is there a built-in method to do the same?
-
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; document.write("The current month is " + monthNames[d.getMonth()]);
Of course you can capalize the months in the array or use the toUpperCase function. (I know uses an array but its simple) – Trevor Commented Oct 11, 2013 at 18:45 - 1 How's this work: stackoverflow./questions/1643320/… -- From the bottom post: jsfiddle/dstorey/Xgerq – tymeJV Commented Oct 11, 2013 at 18:45
- 'but is there a built-in method to do the same'... simple answer, no. while the syntax itself is en-us, the language is culture agnostic. btw agree with Barmar... moment.js is the way to go if you want to power up JS dates. – James Gaunt Commented Oct 11, 2013 at 18:47
- @JamesGaunt maybe JavaScript doesn't have a method built-in, but there has to be a lib out there that does. – Mr Jones Commented Oct 11, 2013 at 18:48
- 3 Try moment.js, it's the canonical library for date/time-related needs. – Barmar Commented Oct 11, 2013 at 18:48
6 Answers
Reset to default 3Like this, see toLocaleString
While this method has been around for quite some time, it is only recently that browsers have begun to implement the locales
and options
arguments and is therefore not yet widely supported.
Javascript
var today = new Date(),
options = {
month: "long"
},
month = today.toLocaleString("en-GB", options).toUpperCase();
alert(month);
jsFiddle
You may want to consider the JavaScript Date object's function toLocaleString()
. You can specify the locale and format to retrieve.
Javascript does not have a method built in to retrieve the name of the month. You will have to create a method of your own, nearly all of which will use some form of fetching an entry from an Array
of month names.
If you are content with the 3 letter month abbreviation this would work:
d.toDateString().substr(4,3).toUpperCase()
Full disclaimer: I'm not sure if that would be affected by the region or not.
var d=new Date();
var month=['January' , 'February' ,'March', 'April' , 'May' ,'June', 'July' , 'August' ,'September', 'October' , 'November' ,'December'];
var n = month[d.getMonth()];
alert(n);
const today = new Date();
const options = {month: 'long'};
today.toLocaleDateString('it-IT', options);
A way for getting the month from a Date Object.