Is it possible to get a list of all months using vanilla JavaScript? - Stack Overflow

Using vanilla JS, is it possible to get an array of months? For example:['January', ..., 

Using vanilla JS, is it possible to get an array of months? For example:

['January', ..., 'December']

While libraries like moment.js exist and make sense to use rather than reinventing the wheel, sometimes it's desired/necessary to implement in vanilla JS.

Using vanilla JS, is it possible to get an array of months? For example:

['January', ..., 'December']

While libraries like moment.js exist and make sense to use rather than reinventing the wheel, sometimes it's desired/necessary to implement in vanilla JS.

Share Improve this question asked Jul 16, 2017 at 23:50 Rick VisiRick Visi 8,8924 gold badges40 silver badges56 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Date.prototype.toLocaleDateString() can produce month names so it's possible to generate an array of 12 items and map each item's index (0 - 11) to month names.

const months = new Array(12).fill(0).map((_, i) => {
  return new Date(`${i + 1}/1`).toLocaleDateString(undefined, {month: 'long'})
});
console.log(months);

The code above logs the array of months:

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

Here's how it works:

  • new Array(12) initializes a new array of length 12
  • the array can't be mapped until it has some items defined, so .fill(0) initializes all items to 0
  • .map(...) maps all 12 0s of the array
  • (_, i) => { ... } is a function that ignores the first parameter (which is the item itself, in each case it will be 0) and only makes use of the index, which will go from 0 to 11
  • new Date(`${i + 1}/1`) initializes a new date object with the date in the format MM/DD where the month is a 1-based index and the day of the month is always 1. Setting the day is necessary because otherwise it default's to today's date and if it happens to be >28 the month may roll over to the next one (eg if today is 7/31 but i==2, then the date will be initialized with February 31, which doesn't exist, so the Date object just produces a day in May instead)
  • .toLocaleDateString(undefined, {month: 'long'}) is where the magic happens. The object contains a formatMatcher object, which controls how the date is formatted when written out as a string. The month property is set to 'long' so that the full month name (eg "July") is produced. Fun fact: the first argument is undefined so that it doesn't overwrite the user's default locale. This is awesome because a user in France would see the month names in French automatically:

["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]

If you want to keep the months in English, just set this parameter to 'en'.


If it helps, here's the same code rewritten to use older JS grammar:

var months = [];
for (var i = 0; i < 12; i++) {
  var d = new Date((i + 1) + '/1');
  months.push(d.toLocaleDateString(undefined, {month: 'long'}));
}
console.log(months);

I think using setMonth is both more efficient and easier to understand than creating a date from a concatenated string.

const months= [];
const d = new Date();
for(let month = 0; month < 12; ++month) {
   d.setMonth(month);
   months.push(d.toLocaleString(undefined, {month: 'long'}));
}

console.log(months);

You can also use new Date(0, month) if you prefer the look of it. Less efficient than setMonth as it builds 12 Date objects rather than re-using one, but slightly shorter.

const months = (locales) =>
  [...Array(12)].map((_item, index) =>
    new Date(0, index).toLocaleString(locales, { month: "long" })
  );

console.log({ en: months("en"), es: months("es") });

Output

{
  en: [
    'January',   'February',
    'March',     'April',
    'May',       'June',
    'July',      'August',
    'September', 'October',
    'November',  'December'
  ],
  es: [
    'enero',      'febrero',
    'marzo',      'abril',
    'mayo',       'junio',
    'julio',      'agosto',
    'septiembre', 'octubre',
    'noviembre',  'diciembre'
  ]
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744300395a4567472.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信