Как получить текущий год в JavaScript?
Получить текущий год в JavaScript
Ответ 1
Создайте new Date()
объект new Date()
и вызовите getFullYear()
:
new Date().getFullYear()
// returns the current year
Перехват принятого ответа для предоставления некоторого базового примера контекста, такого как нижний колонтитул, который всегда показывает текущий год:
<footer>
© <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>
© <span id="year">2018</span> by FooBar
</footer>
Ответ 2
// Return today 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
для текущего года мы можем использовать getFullYear() из класса Date, однако есть много функций, которые вы можете использовать согласно требованиям, некоторые функции таковы,
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 day is: " + day);
Ответ 5
Вот как я встраиваю и выводлю его на мою HTML-страницу:
<div class="container">
<p class="text-center">Copyright ©
<script>
var CurrentYear = new Date().getFullYear()
document.write(CurrentYear)
</script>
</p>
</div>
Вывод на HTML-страницу выглядит следующим образом:
Авторское право © 2018
Ответ 6
Вы можете просто использовать JavaScript, как это. В противном случае вы можете использовать плагин momentJs, который помогает в больших приложениях.
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)
function generate(type,element)
{
var value = "";
var date = new Date();
switch (type) {
case "Date":
value = date.getDate(); // Get the day as a number (1-31)
break;
case "Day":
value = date.getDay(); // Get the weekday as a number (0-6)
break;
case "FullYear":
value = date.getFullYear(); // Get the four digit year (yyyy)
break;
case "Hours":
value = date.getHours(); // Get the hour (0-23)
break;
case "Milliseconds":
value = date.getMilliseconds(); // Get the milliseconds (0-999)
break;
case "Minutes":
value = date.getMinutes(); // Get the minutes (0-59)
break;
case "Month":
value = date.getMonth(); // Get the month (0-11)
break;
case "Seconds":
value = date.getSeconds(); // Get the seconds (0-59)
break;
case "Time":
value = date.getTime(); // Get the time (milliseconds since January 1, 1970)
break;
}
$(element).siblings('span').text(value);
}
li{
list-style-type: none;
padding: 5px;
}
button{
width: 150px;
}
span{
margin-left: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<button type="button" onclick="generate('Date',this)">Get Date</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('Day',this)">Get Day</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('FullYear',this)">Get Full Year</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('Hours',this)">Get Hours</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('Milliseconds',this)">Get Milliseconds</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('Minutes',this)">Get Minutes</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('Month',this)">Get Month</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('Seconds',this)">Get Seconds</button>
<span></span>
</li>
<li>
<button type="button" onclick="generate('Time',this)">Get Time</button>
<span></span>
</li>
</ul>
Ответ 7
Возьмите этот пример, вы можете разместить его там, где хотите показать, не обращаясь к скрипту в нижнем колонтитуле или где-то еще, как другие ответы
<script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>
Примечание об авторских правах в нижнем колонтитуле в качестве примера
Copyright 2010 - <script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>
Ответ 8
Просто и быстро:
new Date().getFullYear()
Ответ 9
Просто используйте getFullYear()
для вашего объекта Date()
...
const currentYear = new Date().getFullYear(); //currentYear = 2019
Ответ 10
чтобы упростить все операции, связанные с временем, может иметь смысл использовать индивидуальную библиотеку, такую как момент js, текущий год по местному времени будет (возвращает 4digit year как Number):
moment().year();
или в UTC время:
moment().utc().year();