Shyju
Shyju

Reputation: 218862

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

Upvotes: 1055

Views: 1540639

Answers (30)

Zoe L
Zoe L

Reputation: 1500

quick and easy

new Date("10/11/2009").toLocaleString("en-US", { month: "long" })
// 'October'

Upvotes: 15

zumalifeguard
zumalifeguard

Reputation: 9016

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

Upvotes: 5

Bayram
Bayram

Reputation: 221

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.

Upvotes: 13

Undertaker
Undertaker

Reputation: 131

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

Upvotes: -4

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20118

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"

Upvotes: 89

Mitanshu
Mitanshu

Reputation: 869

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"

Upvotes: 52

Rahul Pandey
Rahul Pandey

Reputation: 191

You can try this:

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

console.log(t[2] + " " + t[1] + " " + t[3]);

Upvotes: 6

HAJJAJ
HAJJAJ

Reputation: 3787

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

Upvotes: 4

navule
navule

Reputation: 3654

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

Upvotes: 8

Andres Paul
Andres Paul

Reputation: 1078

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

Upvotes: 37

Tron
Tron

Reputation: 636

It can be done as follows too:

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

Upvotes: 5

Prasanna Jathan
Prasanna Jathan

Reputation: 590

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

Upvotes: 5

AzizStark
AzizStark

Reputation: 1514

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

Upvotes: 24

Kratak
Kratak

Reputation: 51

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

Upvotes: 5

David Storey
David Storey

Reputation: 30424

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.

Upvotes: 1560

venkat7668
venkat7668

Reputation: 2777

Another way to format date

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

Upvotes: 22

Jesper
Jesper

Reputation: 206936

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.

Upvotes: 1481

Brian M. Hunt
Brian M. Hunt

Reputation: 83828

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.

Upvotes: 77

M.A.K. Ripon
M.A.K. Ripon

Reputation: 2148

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

Upvotes: 21

James Heazlewood
James Heazlewood

Reputation: 930

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

Upvotes: -1

John Slegers
John Slegers

Reputation: 47121

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

Upvotes: -1

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4608

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.

Upvotes: 5

beneus
beneus

Reputation: 161

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

Upvotes: 16

Kanchan
Kanchan

Reputation: 1619

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

Upvotes: 2

Beena Shetty
Beena Shetty

Reputation: 3736

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

Upvotes: 25

Anand kumar
Anand kumar

Reputation: 161

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

Upvotes: 15

lnmunhoz
lnmunhoz

Reputation: 115

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

Upvotes: 3

shacharsol
shacharsol

Reputation: 2342

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

Upvotes: 7

user3920942
user3920942

Reputation: 55

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;

Upvotes: 3

Matt K
Matt K

Reputation: 6708

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.

Upvotes: 4

Related Questions