从日期中获取月份的名称
Get the Month Name from a Date in JavaScript
从日期中获取月份的名称:
new Date()
使用构造函数创建日期对象。toLocaleString()
在日期对象上调用方法,month
在选项对象中设置属性。- 该
toLocaleString()
方法将返回月份的名称。
索引.js
// 👇️ February 24th const date = new Date(2025, 01, 24); const nameOfMonth = date.toLocaleString('default', { month: 'long', }); console.log(nameOfMonth); // 👉️ February
我们使用new Date()
构造函数创建了一个Date
对象
。
我们传递给 Date 方法的参数是年、月和日。
月份索引在 JavaScript 中是从零开始的,这意味着一月是
0
,十二月是11
。下一步是调用对象的
toLocaleString
方法,并向其Date
传递以下参数。
- 语言环境– 应返回月份名称的语言。通过指定
default
,它可以根据用户的浏览器首选项而有所不同。 - 选项对象– 我们将设置
month
设置long
为获取月份的全名。其他可能的值是short
和narrow
。
如果要获取不同语言环境中的月份名称,请将语言环境作为第一个参数传递给该方法。
索引.js
const date = new Date(2025, 01, 24); const nameOfMonthUS = date.toLocaleString('en-US', { month: 'long', }); console.log(nameOfMonthUS); // 👉️ February const nameOfMonthDE = date.toLocaleString('de-DE', { month: 'long', }); console.log(nameOfMonthDE); // 👉️ Februar
如果您需要以不同的格式获取月份名称,例如前 3 个字母,或仅第一个字母,请更新month
选项对象中的属性值。
索引.js
// 👇️ February console.log(date.toLocaleString('en-US', {month: 'long'})); // 👇️ Feb console.log(date.toLocaleString('en-US', {month: 'short'})); // 👇️ F console.log(date.toLocaleString('en-US', {month: 'narrow'}));
将月份设置为long
,为我们提供月份的完整名称。该short
值为我们提供3
了月份的第一个字母,并且narrow
– 只是第一个字母。