theme: vuepress
了解如何使用 JavaScript 通过其在 12 个月列表中的位置来获取月份的名称。
日期的 toLocaleString() 方法
使用 Date.toLocaleString() 即可将日期转换成指定的月份,例如获取当前月份,我们想要显示出来的效果是:1月。
const date = new Date();
console.log(date.toLocaleString('zh-cn', { month: 'long' })) // 七月
当然,如果想要输出英文,那么只需要将 zh-cn 替换为 en-us 即可:
const date = new Date();
console.log(date.toLocaleString('en-us', { month: 'long' })) //July
这个函数一共需要两个参数:
locales: 带有 BCP 47 语言标签的字符串,或此类字符串的数组。我们可以指定许多语言环境,例如zn-cn汉语、en-GB英国英语和en-CA加拿大英语。
options: 用于调整日期输出格式的对象。
在我们的示例中,我们作为语言标签传递以使用汉语,并为选项对象的属性zh-cn设置一个mounth为long的值以显示完整的月份名称。
我们可以传递一个空数组 ([])作为第一个参数来toLocaleString()使用浏览器的默认语言环境:
const date = new Date();
date.toLocaleString([], { month: 'long' })
这有利于国际化,因为输出会根据用户的首选语言而有所不同。
除了属性long,我们还可以指定其他值。month例如,我们可以使用short将月份名称缩写为三个字母:
这里主要说英语,原因有两点:
- 汉语表达月份的字符长度很短
- 除了英语外我不懂的其他语言表达月份
const date = new Date();
date.toLocaleString('en-US', { month: 'short' }); //Jul
这样就可以把英文月份的简拼显示出来,实在是方便。
使用toLocaleString()意味着你必须指定一个locale和options每次你想要一个语言敏感的字符串。要使用相同的设置来格式化多个日期,我们可以使用Intl.DateTimeFormat类的对象来代替。
function getTwoConsecutiveMonthNames(monthNumber) {
const date1 = new Date();
date1.setMonth(monthNumber - 1);
const date2 = new Date();
date2.setMonth(monthNumber);
const formatter = new Intl.DateTimeFormat('zn-cn', { month: 'long' });
// Format both dates with the same locale and options
const firstMonth = formatter.format(date1);
const secondMonth = formatter.format(date2);
return `${firstMonth} & ${secondMonth}`;
}
console.log(getTwoConsecutiveMonthNames(1)); // 一月 & 二月
console.log(getTwoConsecutiveMonthNames(2)); // 二月 & 三月
console.log(getTwoConsecutiveMonthNames(3)); // 三月 & 四月