Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to get the month name of the current date without setting an array of month names? [duplicate]

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");
like image 427
Shyju Avatar asked Nov 21 '22 00:11

Shyju


2 Answers

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.

like image 89
Jesper Avatar answered Dec 06 '22 00:12

Jesper


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.

like image 24
David Storey Avatar answered Dec 06 '22 02:12

David Storey