在 JavaScript 中获取当前年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6002254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:49:46  来源:igfitidea点击:

Get the current year in JavaScript

javascriptdate

提问by Satch3000

How do I get the current year in JavaScript?

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

回答by Jason Harwig

Create a new Date()object and call getFullYear():

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

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


HiHymaning the accepted answer to provide some basic example context like a footer that always shows the current year:

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

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

Somewhere else executed after the HTML above has been loaded:

在上面的 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>

回答by Sourav

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

回答by Parth Jasani

Here is another method to get date

这是获取日期的另一种方法

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)

回答by Jerusalem Programmer

Such is how I have it embedded and outputted to my HTML web page:

这就是我将它嵌入并输出到我的 HTML 网页的方式:

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

Output to HTML page is as follows:

输出到 HTML 页面如下:

Copyright ? 2018

版权?2018年

回答by Rupesh Agrawal

for current year we can use getFullYear() from Dateclass however there are many function which you can use as per the requirements, some functions are as,

对于当前年份,我们可以使用Date类中的getFullYear()但是有许多函数可以根据要求使用,有些函数是,

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

回答by Majali

Take this example, you can place it wherever you want to show it without referring to script in the footer or somewhere else like other answers

拿这个例子来说,你可以把它放在任何你想显示的地方,而不用在页脚或其他地方引用脚本,比如其他答案

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

Copyright note on the footer as an example

以页脚版权说明为例

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

回答by Nishal K.R

You can simply use javascript like this. Otherwise you can use momentJsPlugin which helps in large application.

您可以像这样简单地使用 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>

回答by Consta Gorgan

TL;DR

TL; 博士

Most of the answers found here are correct onlyif you need the current year based on your localmachine's time zone and offset (client side) - source which, in most scenarios, cannot be considered reliable (beause it can differ from machine to machine).

当您需要基于本地机器的时区和偏移量(客户端)的当前年份时,此处找到的大多数答案才是正确的- 来源在大多数情况下,不能被认为是可靠的(因为它可能因机器而异) .

Reliable sources are:

可靠的来源是:

  • Web server's clock (but make sure that it's updated)
  • Time APIs & CDNs
  • Web 服务器的时钟(但要确保它已更新)
  • 时间 API 和 CDN

Details

细节

A method called on the Dateinstance will return a value based on the local time of your machine.

Date实例上调用的方法将根据您机器的本地时间返回一个值。

Further details can be found in "MDN web docs": JavaScript Date object.

更多细节可以在 "MDN web docs": JavaScript Date object 中找到

For your convenience, I've added a relevant note from their docs:

为方便起见,我从他们的文档中添加了相关注释:

(...) the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.

(...) 获取日期和时间或其组件的基本方法都在本地(即主机系统)时区和偏移量中工作。

Another source mentioning this is: JavaScript date and time object

提到这一点的另一个来源是:JavaScript 日期和时间对象

it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different times from the one created on your own computer.

需要注意的是,如果某人的时钟偏离了几个小时或者他们处于不同的时区,那么 Date 对象将创建与在您自己的计算机上创建的时间不同的时间。

Some reliable sources that you can use are:

您可以使用的一些可靠来源是:

But if you simply don't care about the time accuracy or if your use case requires a time value relative to local machine's time then you can safely use Javascript's Datebasic methods like Date.now(), or new Date().getFullYear()(for current year).

但是,如果您根本不关心时间准确性,或者您的用例需要相对于本地机器时间的时间值,那么您可以安全地使用 Javascript 的Date基本方法,例如Date.now(), or new Date().getFullYear()(对于当前年份)。