Get the current year in JavaScript
如何在JavaScript中获取当前年份?
创建
1 2 | new Date().getFullYear() // returns the current year |
劫持已接受的答案,提供一些基本的示例上下文,如页脚始终显示当前年份:
1 2 3 | <footer> © <span id="year">2018</span> </footer> |
在上面的HTML加载后执行的其他地方:
1 | document.getElementById("year").innerHTML = new Date().getFullYear(); |
1 | document.getElementById("year").innerHTML = new Date().getFullYear(); |
1 2 3 4 | footer { text-align: center; font-family: sans-serif; } |
1 2 3 | <footer> © <span id="year">2018</span> by FooBar </footer> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 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) |
这是另一种获取日期的方法
1 2 3 4 5 6 7 8 9 | 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) |
对于今年我们可以使用Date类的getFullYear()但是有很多功能你可以按照要求使用,有些功能是,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var now = new Date() console.log("Current Time is:" + now); // getFullYear function will give current year var currentYear = now.getFullYear() console.log("Current year is:" + currentYear); // getYear will give you the years after 1990 i.e currentYear-1990 var year = now.getYear() console.log("Current year is:" + year); // getMonth gives the month value but months starts from 0 // add 1 to get actual month value var month = now.getMonth() + 1 console.log("Current month is:" + month); // getDate gives the date value var day = now.getDate() console.log("Today's day is:" + day); |
你可以简单地使用这样的javascript。 否则你可以使用momentJs插件,这有助于大型应用程序。
1 2 3 4 5 6 7 8 9 | 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) |
这就是我将它嵌入并输出到我的HTML网页的方式:
1 2 3 4 5 6 7 | <p class="text-center">Copyright © var CurrentYear = new Date().getFullYear() document.write(CurrentYear) </p> |
输出到HTML页面如下:
版权?2018