如何在JavaScript中获取当前年份?


当前回答

您可以用一行JS代码获取当前年份。

<p>版权所有<script>document.write(newDate().getFullYear())</脚本></p>

其他回答

实例化类Date并调用其getFullYear方法以获取yyyy格式的当前年份。类似于:

let currentYear = new Date().getFullYear();

currentYear变量将保存您要查找的值。

// Return today's date and time
var currentTime = new Date()

// returns the month (from 0 to 11)
var month = currentTime.getMonth() + 1

// returns the day of the month (from 1 to 31)
var day = currentTime.getDate()

// returns the year (four digits)
var year = currentTime.getFullYear()

// write output MM/dd/yyyy
document.write(month + "/" + day + "/" + year)

下面是获取日期的另一种方法

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

如果您将ES6 Javascript与Angular、React、VueJS等框架一起使用。然后,您应该集成第三方实用程序库,以方便您的项目。DayJS是最流行的轻量级库之一,具有不可变的数据结构。在dayJS中,您可以在一行简单的代码中获得年份,如下所示。

dayjs().year()

还有很多有用的方法。所以我建议你在下一个项目中使用dayjs。

创建一个新的Date()对象并调用getFullYear():

new Date().getFullYear()  // returns the current year

示例用法:始终显示当前年份的页脚:

document.getElementById(“年”).innerHTML=新日期().getFullYear();页脚{文本对齐:居中;字体系列:无衬线;}<页脚>©唐老鸭(Donald Duck)的<span id=“year”></span></footer>

另请参见Date()构造函数的完整方法列表。