在 JavaScript 中获取当前年份
2022-08-29 22:02:26
如何在 JavaScript 中获取当前年份?
创建一个新的 Date()
对象并调用 getFullYear()
:
new Date().getFullYear() // returns the current year
用法示例:始终显示当前年份的页面页脚:
document.getElementById("year").innerHTML = new Date().getFullYear();
footer {
text-align: center;
font-family: sans-serif;
}
<footer>
©<span id="year"></span> by Donald Duck
</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)