从 JavaScript 中的日期获取月份名称

从日期中获取月份的名称

Get the Month Name from a Date in JavaScript

从日期中获取月份的名称:

  1. new Date()使用构造函数创建日期对象。
  2. toLocaleString()在日期对象上调用方法,month
    在选项对象中设置属性。
  3. 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传递以下参数。

  1. 语言环境– 应返回月份名称的语言通过指定default,它可以根据用户的浏览器首选项而有所不同。
  2. 选项对象– 我们将设置month设置long为获取月份的全名。其他可能的值是shortnarrow

如果要获取不同语言环境中的月份名称,请将语言环境作为第一个参数传递给该方法。

索引.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– 只是第一个字母。

进一步阅读

发表评论