997

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");
John Slegers
  • 45,213
  • 22
  • 199
  • 169
Shyju
  • 214,206
  • 104
  • 411
  • 497

41 Answers41

1470

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.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 465
    it is a bit frustrating that even having `new Date()` returning `Tue Sep 06 2011 20:02:25 GMT+0200 (CEST)` which clearly means the Date object already has all this internally defined (month and week day names) it is not public, so we have to type it all again. :( – zanona Sep 06 '11 at 18:04
  • 9
    Not an ideal solution if one has to include month names for each language supported. There's got to be a better way using `String#split` with `toString` or `toDateString`. – rxgx Oct 31 '11 at 19:18
  • 24
    multiple languages = multi-dimensional array ;) translations["monthName"][currentLanguage][d.getMonth()] – nuala Dec 30 '11 at 15:18
  • 29
    @zanona—a date object doesn't necessarily have "all this internally defined". All that is required in ECMA-262 is a [time value](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1), which is a number. What you are seeing is the result of [*Date.prototype.toString*](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.5.2), which is implementation dependent. – RobG May 23 '13 at 23:02
  • 2
    or just `'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ')[new Date().getMonth()]` – Devin Rhode Jul 03 '13 at 19:18
  • 9
    @Devin but that reallocates the array each time you want to access it. – Cole Tobin Sep 06 '13 at 01:10
  • Since the array is zero based, if you want to get the month say January and you pass 1 you will get undfined Need month - 1 var mo = (monthNames[d.getMonth() - 1) – Elim Garak Sep 15 '16 at 16:45
  • 3
    @RegencySoftware Yes, but note that `Date.getMonth()` is also zero-based (it returns 0-11 for the months rather than 1-12, which would be more logical for humans). – Jesper Sep 15 '16 at 17:50
  • could be late but `moment.months().map((month, index) => ({ label: month, value: index }))` did a good trick for me (if using momentjs) – Ethaan Dec 13 '17 at 02:27
  • 2
    This is way outdated, use the `toLocaleString` solution provided by David Storey instead – YakovL Aug 22 '18 at 14:19
  • 1
    I would use the Internationalization API. See [David Storey's answer](https://stackoverflow.com/a/18648314/6086226). – Derk Jan Speelman Mar 08 '19 at 07:47
  • 1
    I don't understand why this is such a popular answer and why people keep upvoting it even 10 years after I wrote it... – Jesper Sep 28 '19 at 20:46
  • You can also write like this const d = new Date(); d.toLocaleString('default', { month: 'short' }) d.toLocaleString('default', { month: 'long' }) – kantsverma Jan 21 '21 at 06:20
  • It's actually not outdated at least with typescript, because I couldn't make timeStyle: 'short' to work with Intl.datetimeformat(). This is still the best method. – Don Dilanga Mar 16 '21 at 05:05
  • Downvoting as this is obsolete – Sklivvz Dec 10 '21 at 08:26
1463

It is now possible to do this with the ECMAScript Internationalization API:

const date = new Date(2009, 10, 10);  // 2009-11-10
const month = date.toLocaleString('default', { month: 'long' });
console.log(month);

'long' uses the full name of the month, 'short' for the short name, and 'narrow' for a more minimal version, such as the first letter in alphabetical languages.

You can change the locale from browser's 'default' to any that you please (e.g. 'en-us'), and it will use the right name for that language/country.

With toLocaleStringapi you have to pass in the locale and options each time. If you are going do use the same locale info and formatting options on multiple different dates, you can use Intl.DateTimeFormat instead:

const formatter = new Intl.DateTimeFormat('fr', { month: 'short' });
const month1 = formatter.format(new Date());
const month2 = formatter.format(new Date(2003, 5, 12));
console.log(`${month1} and ${month2}`); // current month in French and "juin".

For more information see my blog post on the Internationalization API.

Boghyon Hoffmann
  • 17,103
  • 12
  • 72
  • 170
David Storey
  • 29,166
  • 6
  • 50
  • 60
  • 1
    I can confirm that the Safari Technology Preview has support for this. I think should be the accepted answer – Salman Hasrat Khan May 02 '16 at 12:03
  • 1
    Works in node too! – mikemaccana Jan 09 '17 at 12:15
  • 7
    Great solution, but for my use case this ended up being too slow. I was processing several hundred items and it was averaging about 1ms per item to get both the month and year (chrome, safari). I ended up using the accepted answer but only because it performed much better. This would be my preferred method if I only needed to call it a few times. – t.888 Nov 17 '17 at 01:19
  • 9
    This is now supported on most browsers: https://caniuse.com/#search=intl – eyal83 Apr 22 '18 at 09:30
  • 9
    Note on React Native, this works for iOS devices, but on Android, it displays incorrectly (just spits out the entire timestamp). – hardanger May 10 '19 at 14:17
  • 1
    @t.888 Have you tried using `Intl.DateTimeFormat`? MDN explicitly mentions to favor it over `date.toLocaleString` if multiple items need to be processed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Performance – Boghyon Hoffmann Jul 10 '19 at 18:15
  • This solution is simple and works fine in react JS. I used short to get Jan, Feb etc. – AmitG Apr 08 '20 at 16:43
  • 2
    Note that this doesn't work on any version of IE (for everyone with enterprise clients). – bsplosion Aug 31 '20 at 16:11
  • This works in IE if you replace 'default' with undefined – Curtis Oct 01 '21 at 05:05
  • @JESii `date.toLocaleFormat` is deprecated, `date.toLocaleString` is not – keeri Jan 19 '22 at 14:56
  • @keeri you're right. Thanks for catching that typo-deleted since I can't edit it! – JESii Jan 21 '22 at 13:47
174

Here's another one, with support for localization :)

Date.prototype.getMonthName = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names[this.getMonth()];
};

Date.prototype.getMonthNameShort = function(lang) {
    lang = lang && (lang in Date.locale) ? lang : 'en';
    return Date.locale[lang].month_names_short[this.getMonth()];
};

Date.locale = {
    en: {
       month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
       month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    }
};

you can then easily add support for other languages:

Date.locale.fr = {month_names: [...]};
Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
krcko
  • 2,834
  • 1
  • 16
  • 11
  • 2
    Note **this won't work on node** as of 6.x as `Date.locale` is `undefined`. it's an excellent answer for other JS implementations though! – mikemaccana Jan 09 '17 at 12:13
  • This might make sense if the localised name arrays were built using *Date.prototype.toLocaleString*. Also, extending built-in prototypes and objects is not considered a good idea. – RobG Nov 20 '18 at 22:33
80

If we need to pass our input then we need to use the following way

input: '2020-12-28'

Code:

new Date('2020-12-28').toLocaleString('en-us',{month:'short', year:'numeric'})

Output: "Dec 2020"

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
77

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.

Nivin V Joseph
  • 12,042
  • 2
  • 15
  • 24
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
  • 3
    The first one would result in "Apr". "MMM" shows the first three letters of the month, if you want the full name use "MMMM" instead. See their [documentation](http://momentjs.com/docs/#/displaying/format/) for help. – Tomnar Apr 22 '17 at 17:47
  • If you're going the route of heavy optimization and reducing http requests, this may not be an option for you. Instead, stick with just using an array of month names if you are only going to format the month names in one line of code. – OzzyTheGiant Jul 19 '17 at 18:53
  • 5
    Moment is a [very](https://github.com/moment/moment/issues/3376) large library, and way overkill for this. Modern alternatives include `Luxon` and `date-fns`, but then again, there is [wide browser support for the Internationalization API nowadays](https://stackoverflow.com/questions/1643320/get-month-name-from-date#comment86944935_18648314). – Dan Dascalescu Dec 25 '18 at 02:44
  • 1
    moment.js is deprecated see https://github.com/you-dont-need/You-Dont-Need-Momentjs – GorvGoyl Jan 11 '21 at 17:16
66

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.

nickf
  • 537,072
  • 198
  • 649
  • 721
  • 6
    "and there are some good reasons to not want to do this". Just curious: which reasons do you mean? – KooiInc Nov 20 '10 at 11:09
  • 15
    @Kooilnc: It's because you're essentially working in the global space. If you import someone else's functions or libraries which also do this, then they could be overwriting each other. – nickf Nov 22 '10 at 08:50
43

If you are in hurry...then here you go!

const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}

Expected Output: "Apr"

Mitanshu
  • 717
  • 7
  • 11
37

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

Andres Paul
  • 1,020
  • 16
  • 18
25
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();
Beena Shetty
  • 3,676
  • 2
  • 28
  • 31
24

document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))
AzizStark
  • 1,390
  • 1
  • 17
  • 27
  • you can add time as well: `new Date().toLocaleString('he-il',{month:'long', year:'numeric', day:'numeric', hour: 'numeric', minute:'numeric', second: 'numeric'});` – Nadav Dec 29 '21 at 18:29
21

Some common easy process from date object can be done by this.

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

function dateFormat1(d) {
  var t = new Date(d);
  return t.getDate() + ' ' + monthNames[t.getMonth()] + ', ' + t.getFullYear();
}

function dateFormat2(d) {
  var t = new Date(d);
  return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear();
}

console.log(dateFormat1(new Date()))
console.log(dateFormat2(new Date()))

Or you can make date prototype like

Date.prototype.getMonthName = function() {
  var monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
  return monthNames[this.getMonth()];
}


Date.prototype.getFormatDate = function() {
  var monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
  return this.getDate() + ' ' + monthNames[this.getMonth()] + ', ' + this.getFullYear();
}


console.log(new Date().getMonthName())
console.log(new Date().getFormatDate())

Ex:

var dateFormat3 = new Date().getMonthName(); # March

var dateFormat4 = new Date().getFormatDate(); # 16 March, 2017

M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
20

Another way to format date

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"
venkat7668
  • 2,657
  • 1
  • 22
  • 26
18

You might use datejs to do that. Check the FormatSpecifiers, MMMM gives you the month's name:

var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));

And datejs got that localized for more than 150 locales! See here

Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
16

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"});
rocambille
  • 15,398
  • 12
  • 50
  • 68
beneus
  • 161
  • 1
  • 2
15

Instead of declaring array which hold all the month name and then pointing with an index, we can also write it in a shorter version as below:

var objDate = new Date().toLocaleString("en-us", { month: "long" }); // result: August
var objDate = new Date().toLocaleString("en-us", { month: "short" }); // result: Aug
Denis Bubnov
  • 2,619
  • 5
  • 30
  • 54
Anand kumar
  • 161
  • 1
  • 8
  • please note that this doesn't work reliably across browsers... Safari (mobile and desktop) will output something like that: `MAY 1, 2015 AT 12:00:00 AM GMT-4` (when using `{ month: "long" }` parameters) – David M. Aug 24 '16 at 17:19
  • 1
    you can also get the default using `new Date().toLocaleString(navigator.language, { month: "short" })` – Remo H. Jansen Oct 25 '16 at 13:05
14

Here's a way that does not depend on a hard-coded array and supports multiple locales.

If you need a whole array:

var monthsLocalizedArray = function(locale) {
    var result = [];
    for(var i = 0; i < 12; i++) {
        result.push(new Date(2010,i).toLocaleString(locale,{month:"long"}));
    }
    return result;
};

Usage:

console.log(monthsLocalizedArray('en')); // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
console.log(monthsLocalizedArray('bg')); // -> ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"]

If you need only a selected month (faster):

var monthLocalizedString = function(month, locale) {
    return new Date(2010,month).toLocaleString(locale,{month:"long"});
};

Usage:

console.log(monthLocalizedString(1, 'en')); // -> February
console.log(monthLocalizedString(1, 'bg')); // -> февруари
console.log(monthLocalizedString(1, 'de')); // -> Februar

Tested and works fine on Chrome and IE 11. On mozilla some modifications are needed, because it returns the whole date.

13

The easiest and simplest way:

const dateStr = new Date(2020, 03, 10).toDateString(); // 'Fri Apr 10 2020'
const dateStrArr = dateStr.split(' '); // ['Fri', 'Apr', '10', '2020']
console.log(dateStrArr[1]); // 'Apr'
  1. Convert the date to a string.
  2. Split by ' ' a space.
  3. Select second element of from array.
Bayram
  • 181
  • 2
  • 11
9

Unfortunately the best way to extract the month name is from the UTCString representation:

Date.prototype.monthName = function() {
    return this.toUTCString().split(' ')[2]
};

d = new Date();
//=> Thu Mar 06 2014 23:05:21 GMT+0000 (GMT)

d.monthName();
//=> 'Mar'
Yacoby
  • 54,544
  • 15
  • 116
  • 120
Aaron Cronin
  • 2,093
  • 14
  • 13
8

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);
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
navule
  • 3,212
  • 2
  • 36
  • 54
7

You can use one of several available Date formatters. Since this falls within the JavaScript specification, it will be available in both browser and server-side modes.

objDate.toString().split(" ")[1]; // gives short name, unsure about locale 
objDate.toLocaleDateString.split(" ")[0]; // gives long name

e.g.

js> objDate = new Date(new Date() - 9876543210)
Mon Feb 04 2013 12:37:09 GMT-0800 (PST)
js> objDate.toString().split(" ")[1]
Feb
js> objDate.toLocaleString().split(" ")[0]
February

There are more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Dinesh
  • 4,437
  • 5
  • 40
  • 77
7

The natural format this days is to use Moment.js.

The way to get the month in a string format , is very simple in Moment.js no need to hard code the month names in your code: To get the current month and year in month name format and full year (May 2015) :

  moment(new Date).format("MMMM YYYY");
shacharsol
  • 2,326
  • 20
  • 14
  • with moment already installed for other purposes, this is the simplest solution. – Apps-n-Add-Ons May 15 '18 at 11:04
  • 1
    Moment is a [very](https://github.com/moment/moment/issues/3376) large library, and way overkill for this. Modern alternatives include `Luxon` and `date-fns`, but then again, there is [wide browser support for the Internationalization API nowadays](https://stackoverflow.com/questions/1643320/get-month-name-from-date#comment86944935_18648314). – Dan Dascalescu Dec 25 '18 at 02:47
6

You can try this:

let d = new Date(),
  t = d.toDateString().split(" ");

console.log(t[2] + " " + t[1] + " " + t[3]);
OXiGEN
  • 2,041
  • 25
  • 19
Rahul Pandey
  • 173
  • 3
  • 4
5

This can be also done if you are using kendo.

kendo.toString(dateobject, "MMMM");

Here are list of formatters from kendo site:

"d" Renders the day of the month, from 1 through 31.

"dd" The day of the month, from 01 through 31.

"ddd" The abbreviated name of the day of the week.

"dddd" The full name of the day of the week.

"f" The tenths of a second in a date and time value.

"ff" The hundredths of a second in a date and time value.

"fff" The milliseconds in a date and time value.

"M" The month, from 1 through 12.

"MM" The month, from 01 through 12.

"MMM" The abbreviated name of the month.

"MMMM" The full name of the month.

"h" The hour, using a 12-hour clock from 1 to 12.

"hh" The hour, using a 12-hour clock from 01 to 12.

"H" The hour, using a 24-hour clock from 1 to 23.

"HH" The hour, using a 24-hour clock from 01 to 23.

"m" The minute, from 0 through 59.

"mm" The minute, from 00 through 59.

"s" The second, from 0 through 59.

"ss" The second, from 00 through 59.

"tt" The AM/PM designator.

"yy" The last two characters from the year value.

"yyyy" The year full value.

"zzz" The local timezone when using formats to parse UTC date strings.

Community
  • 1
  • 1
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
5

For me this is best solution is,

for TypeScript as well

const env = process.env.REACT_APP_LOCALE || 'en';

const namedMonthsArray = (index?: number): string[] | string => {
  const months = [];

  for (let month = 0; month <= 11; month++) {
    months.push(
      new Date(new Date('1970-01-01').setMonth(month))
        .toLocaleString(env, {
          month: 'long',
        })
        .toString(),
    );
  }
  if (index) {
    return months[index];
  }
  return months;
};

Output is

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Kratak
  • 51
  • 1
  • 2
5

You can handle with or without translating to the local language

  1. Generates value as "11 Oct 2009"

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())
}
  1. The ECMAScript Internationalization API to translate month to local language (eg: 11 octobre)

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'
  }))
}
Prasanna Jathan
  • 570
  • 7
  • 12
5

It can be done as follows too:

var x = new Date().toString().split(' ')[1];    // "Jul"
Tron
  • 566
  • 6
  • 7
  • This solution shouldn't be used. There is a specific method for getting the month in string which other answers pointed out, no need to extract it from the date directly. With this approach you can't easily switch between languages. – rotimi-best Jan 19 '21 at 14:36
4

If you don't want to use an external library, or store an array of month names, or if the ECMAScript Internationalization API is not good enough because of browser compatibility you can always do it the old-fashioned way by extracting the info from the date output:

var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);

This would give you the abbreviated month name, e.g. Oct. I believe the date will come in all sorts of formats depending on the initialization and your locale so take a look at what toDateString() returns and recalculate your substring() values based on that.

Matt K
  • 6,620
  • 3
  • 38
  • 60
4

To get Date formatted as "dd-MMM-yyyy" using JavaScript use the below code

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ];

    const d = new Date();
    var dd = String(d.getDate()).padStart(2, '0');
    var mm = String(d.getMonth() + 1).padStart(2, '0');
    var yyyy = d.getFullYear();
    var fullDate = +dd +"-"+ monthNames[d.getMonth()] +"-"+ yyyy;
    document.write("The date is : "+ fullDate);
HAJJAJ
  • 3,667
  • 14
  • 42
  • 70
4

Here's a function where you pass in 1 to 12, and returns back the full month name such as 'January' or 'July'

    function getMonthName(monthNumber) {
      return new Date('1999-' + monthNumber + '-15').toLocaleString('en-us', { month: 'long' })
    }
zumalifeguard
  • 8,648
  • 5
  • 43
  • 56
3

If you're using jQuery, you're probably also using jQuery UI, which means you can use $.datepicker.formatDate().

$.datepicker.setDefaults( $.datepicker.regional[ "nl" ] );   // dutch
$.datepicker.formatDate( "dd MM yy", objDate );
mhu
  • 17,720
  • 10
  • 62
  • 93
3

My Best Solution is as follow:

       var dateValue = Date();
       var month = dateValue.substring(4,7);
       var date = dateValue.substring(8,10);
       var year = dateValue.substring(20,24);
       var finaldateString = date+"-"+month+"-"+year;
3

With momentjs, just use the format notation.

const myDate = new Date()
const shortMonthName = moment(myDate).format('MMM') // Aug
const fullMonthName = moment(myDate).format('MMMM') // August
lnmunhoz
  • 115
  • 1
  • 4
  • 2
    Besides this answe having been given 2 times already, `moment` is a [very](https://github.com/moment/moment/issues/3376) large library, and way overkill for this. Modern alternatives include `Luxon` and `date-fns`, but then again, there is [wide browser support for the Internationalization API nowadays](https://stackoverflow.com/questions/1643320/get-month-name-from-date#comment86944935_18648314). – Dan Dascalescu Dec 25 '18 at 02:49
3

quick and easy

new Date("10/11/2009").toLocaleString("en-US", { month: "long" })
// 'October'
Zoe L
  • 1,150
  • 14
  • 22
2

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

rahul
  • 184,426
  • 49
  • 232
  • 263
  • 33
    Why not `var month = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];`? Far shorter than adding them individually... – Fizzix Apr 29 '14 at 02:03
2

If you don't want to use moment and want to display month name -

.config($mdDateLocaleProvider) {
    $mdDateLocaleProvider.formatDate = function(date) {      
      if(date !== null) {
        if(date.getMonthName == undefined) {
          date.getMonthName = function() {
            var monthNames = [ "January", "February", "March", "April", "May", "June", 
            "July", "August", "September", "October", "November", "December" ];
            return monthNames[this.getMonth()];
          }
        }        
        var day = date.getDate();
        var monthIndex = date.getMonth();
        var year = date.getFullYear();
        return day + ' ' + date.getMonthName() + ' ' + year;
      }
    };
  }
Kanchan
  • 1,609
  • 3
  • 22
  • 37
1

I have a partial solution that I came up with. It uses a regular expression to extract the month and day name. But as I look through the Region and Language options (Windows) I realize that different cultures have different format order... maybe a better regular expression pattern could be useful.

function testDateInfo() {
        var months = new Array();
        var days = new Array();
        var workingDate = new Date();
        workingDate.setHours(0, 0, 0, 0);
        workingDate.setDate(1);
        var RE = new RegExp("([a-z]+)","ig");
        //-- get day names 0-6
        for (var i = 0; i < 7; i++) {

            var day = workingDate.getDay();
            //-- will eventually be in order
            if (days[day] == undefined)
                days[day] = workingDate.toLocaleDateString().match(RE)[0];
            workingDate.setDate(workingDate.getDate() + 1);
        }
        //--get month names 0-11
        for (var i = 0; i < 12; i++) {
            workingDate.setMonth(i);
            months.push(workingDate.toLocaleDateString().match(RE)[1]);
        }
        alert(days.join(",") + " \n\r " + months.join(","));
    }
gnat
  • 6,213
  • 108
  • 53
  • 73
Remus
  • 61
  • 7
  • so, minimally it works with english and spanish... id's suspect anything that is DAY, MONTH date, year FORMAT – Remus Sep 12 '12 at 21:45
  • I've looked into it a bit, I think to have a truly language independent solution you would need to have a regular expression that uses UNICODE character ranges. The character ranges would be different for different alphabets so i don't think there would be a one size fits all RegExp that we could use. – Remus Sep 13 '12 at 12:48
0

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.

Tim
  • 2,466
  • 1
  • 21
  • 18
0

To get a array of month name :

Date.monthNames = function( ) {
var arrMonth = [],
    dateRef = new Date(),
    year = dateRef.getFullYear();

dateRef.setMonth(0);
while (year == dateRef.getFullYear()) {
    /* push le mois en lettre et passe au mois suivant */
    arrMonth.push( (dateRef.toLocaleString().split(' '))[2] );
    dateRef.setMonth( dateRef.getMonth() + 1);
}

return arrMonth;
}

alert(Date.monthNames().toString());

// -> janvier,février,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décembre

http://jsfiddle.net/polinux/qb346/

vava
  • 11
0

Just write a simple wrapper around toLocaleString :

function LocalDate(locale) {
  this.locale = locale;
}

LocalDate.prototype.getMonthName = function(date) {
  return date.toLocaleString(this.locale,{month:"long"});
};

var objDate = new Date("10/11/2009");

var localDate = new LocalDate("en");
console.log(localDate.getMonthName(objDate));

localDate.locale = "ru";
console.log(localDate.getMonthName(objDate));

localDate.locale = "zh";
console.log(localDate.getMonthName(objDate));
John Slegers
  • 45,213
  • 22
  • 199
  • 169
0

A quick hack I used which works well:

const monthNumber = 8;
const yearNumber = 2018;
const date = `${['Jan', 'Feb', 'Mar', 'Apr',
  'May', 'Jun', 'Jul', 'Aug',
  'Sep', 'Oct', 'Nov', 'Dec'][monthNumber - 1]
      } ${yearNumber}`;

console.log(date);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
James Heazlewood
  • 862
  • 9
  • 12
-3

I did it via DatePipe.

const datePipe = new DatePipe(this.locale);
datePipe.transform(myDate, 'MMM. y');

You can inject the default locale inside your constructor like this:

constructor(@Inject(LOCALE_ID) private locale: string){}

Reference from Angular https://angular.io/api/common/DatePipe

Undertaker
  • 111
  • 2
  • 13