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 badges3 Answers
Reset to default 7Date.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 to0
.map(...)
maps all 120
s of the array(_, i) => { ... }
is a function that ignores the first parameter (which is the item itself, in each case it will be0
) and only makes use of the index, which will go from0
to11
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 always1
. 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 aformatMatcher
object, which controls how the date is formatted when written out as a string. Themonth
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条)