如何在JavaScript中修复getFullYear()不是一个函数的错误

130 阅读1分钟

在本教程中,我们将学习如何在JavaScript中修复getFullYear()不是一个函数的错误。

当我们试图使用JavaScriptDate().getFullYear() 方法而不使用new关键字时,我们在控制台中得到以下错误。

const year = Date().getFullYear();

console.log(year);
VM381:1 Uncaught TypeError: Date(...).getFullYear is not a function
    at <anonymous>:1:21

要解决getFullYear()不是一个函数的错误,请确保在new Date() 构造函数上调用getFullYear() 方法。

getFullYear() 方法以四位数格式返回当前年份,例如:2022。

下面是一个例子。

const year = new Date().getFullYear();

console.log(year);

输出。

2022

有时,我们需要一个自定义的日期和时间,而不是当前的时间。要做到这一点,我们也可以将标准的日期和时间传递给new Date()构造函数。

下面是一个例子。

const year = new Date('Aug 19, 22 11:20:18').getFullYear();

console.log(year); // 2022