协慌网

登录 贡献 社区

获取 JavaScript 当前年份

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

答案

创建一个new Date()对象并调用getFullYear()

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

劫持已接受的答案,提供一些基本的示例上下文,如页脚始终显示当前年份:

<footer>
    &copy; <span id="year">2018</span>
</footer>

在上面的 HTML 加载后执行的其他地方:

<script>
    document.getElementById("year").innerHTML = new Date().getFullYear();
</script>

document.getElementById("year").innerHTML = new Date().getFullYear();
footer {
  text-align: center;
  font-family: sans-serif;
}
<footer>
    &copy; <span id="year">2018</span> by FooBar
</footer>

// 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)