📜  从时间戳 javascript 中获取月份(1)

📅  最后修改于: 2023-12-03 15:06:36.760000             🧑  作者: Mango

从时间戳 JavaScript 中获取月份

在 JavaScript 中,我们可以使用 Date 对象来处理日期和时间。 日期对象表示从 1970 年 1 月 1 日起的某个时间点。 Unix 时间戳是从该时间点起经过的秒数。要获取时间戳中的月份,我们需要使用 Date 对象的几个方法。

使用 Date 对象获取月份

JavaScript 提供了一种内置方法来将时间戳转换为日期格式,即 new Date(timestamp)。这将返回一个新日期对象,该对象的日期设置为 timestamp 的值。例如:

const timestamp = 1609459200; // 1 Jan 2021
const date = new Date(timestamp * 1000); // Multiply by 1000 to convert from seconds to milliseconds

date 对象的值将是:

Thu Jan 01 2021 00:00:00 GMT+0000 (Coordinated Universal Time)

要获取月份,我们可以使用 getMonth() 方法,该方法返回一个从 0 开始的整数,表示月份。 0 表示一月,1 表示二月,以此类推。

const month = date.getMonth(); // 0 for January, 1 for February, etc.
console.log(month); // Output: 0
使用 Intl.DateTimeFormat 获取月份

另一种获取时间戳中的月份的方法是使用 Intl.DateTimeFormatformat() 方法。 format() 方法以特定于语言环境的方式格式化 Date 对象,并返回字符串表示。 我们可以使用 “M” 选项来获取月份的数字表达形式。

const timestamp = 1609459200; // 1 Jan 2021
const date = new Date(timestamp * 1000); // Multiply by 1000 to convert from seconds to milliseconds

const options = { month: 'numeric' };
const formatter = new Intl.DateTimeFormat('en-US', options);
const month = formatter.format(date); // "1" for January, "2" for February, etc.

console.log(month); // Output: 1

在此示例中,我们使用选项 { month: 'numeric' } 来指示 formatter 对象仅返回月份的数字表示形式。 我们将日志输出为 1,表示这是一月的数字表示形式。

总结

要从 JavaScript 时间戳中获取月份,您可以使用 Date 对象的 getMonth() 方法,该方法返回月份的数字表示形式。 另一种方法是使用 Intl.DateTimeFormatformat() 方法并将 month 选项设置为 “numeric”。

  • 使用 Date 对象的 getMonth() 方法:
const timestamp = 1609459200; // 1 Jan 2021
const date = new Date(timestamp * 1000);

const month = date.getMonth(); // 0 for January, 1 for February, etc.
  • 使用 Intl.DateTimeFormatformat() 方法:
const timestamp = 1609459200; // 1 Jan 2021
const date = new Date(timestamp * 1000);

const options = { month: 'numeric' };
const formatter = new Intl.DateTimeFormat('en-US', options);
const month = formatter.format(date); // "1" for January, "2" for February, etc.