網站搜尋

date - 在 JavaScript 中獲取當前年份


我如何在 JavaScript 中獲取當前年份?

答案#1

建立一個 new 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 Stack Overflow
</footer>

另請參見 Date() 建構函數的 完整方法列表。

答案#2

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

答案#3

這裡有另一種獲取日期的方法

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)

答案#4

你可以用一行 JavaScript 代碼取得當前年份。

<p>Copyright <script>document.write(new Date().getFullYear());</script></p>

答案#5

這就是我如何將它嵌入並輸出到我的 HTML 網頁的方法:

<div class="container">
    <p class="text-center">Copyright &copy; 
        <script>
            var CurrentYear = new Date().getFullYear()
            document.write(CurrentYear)
        </script>
    </p>
</div>

輸出到 HTML 頁面如下:

版權所有 © 2018