[javascript] Get month name from Date

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");

This question is related to javascript date date-format time-format

The answer is


Tested on IE 11, Chrome, Firefox

_x000D_
_x000D_
const dt = new Date();
const locale = navigator.languages != undefined ? navigator.languages[0] : navigator.language;
const fullMonth = dt.toLocaleDateString(locale, {month: 'long'});
console.log(fullMonth);
_x000D_
_x000D_
_x000D_


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.


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


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 );

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.


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

_x000D_
_x000D_
var monthNames = ["January", "February", "March", "April", "May", "June",_x000D_
  "July", "August", "September", "October", "November", "December"_x000D_
];_x000D_
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",_x000D_
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"_x000D_
];_x000D_
_x000D_
function dateFormat1(d) {_x000D_
  var t = new Date(d);_x000D_
  return t.getDate() + ' ' + monthNames[t.getMonth()] + ', ' + t.getFullYear();_x000D_
}_x000D_
_x000D_
function dateFormat2(d) {_x000D_
  var t = new Date(d);_x000D_
  return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear();_x000D_
}_x000D_
_x000D_
console.log(dateFormat1(new Date()))_x000D_
console.log(dateFormat2(new Date()))
_x000D_
_x000D_
_x000D_

Or you can make date prototype like

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

Ex:

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

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


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

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

'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:

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

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


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");

A quick hack I used which works well:

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


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(","));
    }

It can be done as follows too:

var x = new Date().toString().split(' ')[1];    // "Jul"

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;
      }
    };
  }

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"});

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


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

You can handle with or without translating to the local language

  1. Generates value as "11 Oct 2009"

_x000D_
_x000D_
const objDate = new Date("10/11/2009");_x000D_
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']_x000D_
if (objDate !== 'Invalid Date' && !isNaN(objDate)) {_x000D_
  console.log(objDate.getDate() + ' ' + months[objDate.getMonth()] + ' ' + objDate.getFullYear())_x000D_
}
_x000D_
_x000D_
_x000D_

  1. The ECMAScript Internationalization API to translate month to local language (eg: 11 octobre)

_x000D_
_x000D_
const convertDate = new Date('10/11/2009')_x000D_
const lang = 'fr' // de, es, ch _x000D_
if (convertDate !== 'Invalid Date' && !isNaN(convertDate)) {_x000D_
  console.log(convertDate.getDate() + ' ' + convertDate.toLocaleString(lang, {_x000D_
    month: 'long'_x000D_
  }))_x000D_
}
_x000D_
_x000D_
_x000D_


Just write a simple wrapper around toLocaleString :

_x000D_
_x000D_
function LocalDate(locale) {_x000D_
  this.locale = locale;_x000D_
}_x000D_
_x000D_
LocalDate.prototype.getMonthName = function(date) {_x000D_
  return date.toLocaleString(this.locale,{month:"long"});_x000D_
};_x000D_
_x000D_
var objDate = new Date("10/11/2009");_x000D_
_x000D_
var localDate = new LocalDate("en");_x000D_
console.log(localDate.getMonthName(objDate));_x000D_
_x000D_
localDate.locale = "ru";_x000D_
console.log(localDate.getMonthName(objDate));_x000D_
_x000D_
localDate.locale = "zh";_x000D_
console.log(localDate.getMonthName(objDate));
_x000D_
_x000D_
_x000D_


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

_x000D_
_x000D_
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);
_x000D_
_x000D_
_x000D_


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.


The easiest and simplest way I figured.

_x000D_
_x000D_
         var now = new Date();_x000D_
//basically converting whole date to string = "Fri Apr 2020'_x000D_
//then splitting by ' ' a space = ['Fri' 'Apr' '2020']_x000D_
//then selecting second element of array = _x000D_
//['Fri' 'Apr' '2020'].[1]_x000D_
var currentMonth = now.toDateString().split(' ')[1];_x000D_
console.log(currentMonth);_x000D_
         
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))
_x000D_
_x000D_
_x000D_


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"]

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();

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: [...]};

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


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.


You can try this:

var d = new Date();
var t = d.toDateString().split(" ");
t[2] +" "+t[1]+" "+t[3];

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'

Another way to format date

new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}) //output: "May 21, 2019"

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;

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/


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.


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.


You could just simply use Date.toLocaleDateString() and parse the date wanted as parameter

_x000D_
_x000D_
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'}));
_x000D_
_x000D_
_x000D_

You can find more information in the Firefox documentation


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to date-format

Format JavaScript date as yyyy-mm-dd How to format date in angularjs Rails formatting date How to change date format using jQuery? How to format Joda-Time DateTime to only mm/dd/yyyy? Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST Display current time in 12 hour format with AM/PM java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2 Converting a string to a date in a cell

Examples related to time-format

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone How to convert milliseconds to "hh:mm:ss" format? JavaScript seconds to time string with format hh:mm:ss How do I convert datetime to ISO 8601 in PHP Javascript add leading zeroes to date Get month name from Date Getting Hour and Minute in PHP Convert seconds to HH-MM-SS with JavaScript? How to display a date as iso 8601 format with PHP Convert a Unix timestamp to time in JavaScript