【问题标题】:Get the current year in JavaScript在 JavaScript 中获取当前年份
【发布时间】:2011-08-25 12:38:23
【问题描述】:

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

【问题讨论】:

  • 令人惊讶的是,如果真的没有重复的话。 This one 很接近,但不准确。
  • 请注意,对于地球上的每个人来说,“当前”年份不一定相同。必须考虑时区。这里的大多数答案都给出了用户本地时区的当前年份(假设代码在网络浏览器中运行)。
  • 这能回答你的问题吗? Shortest way to print current year in a website
  • 所以每个人都在 8760 中的 24 小时内小心,这不是真的!我的叔叔没有听从这个建议,失去了一个脚趾!

标签: javascript date


【解决方案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 Donald Duck
</footer>

另请参阅Date() 构造函数的full list of methods

【讨论】:

【解决方案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】:

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

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

    输出到 HTML 页面如下:

    版权所有 © 2018

    【讨论】:

    • 我不同意。这显然是一个初学者的问题,我们不应该向任何人传授不好的做法,尤其是那些开始学习基础知识的人。此外,您的答案没有提供任何新信息,因为new Date().getFullYear() 已包含在已接受的答案中。
    • 1.) 不好的做法说你,但其他人不同意,因为这是有效的 vanilla Javascript; 2.) 我的回答提供了有关如何在 HTML 页面中实现这一点的新信息,而不仅仅是 console.log()。
    • “好”是主观的。给猫剥皮的方法不止一种,解决编码问题的方法也不止一种。如果解决方案简单且有效,那么在您的拙见中,为什么这不是“好”?
    • 嗯,先生,很明显这不是一个明确的客观标准(实际上是一个公开辩论),因为有很多人不同意你的观点:stackoverflow.com/questions/802854/… ...和也在这里:stackoverflow.com/questions/18789190/why-not-document-write因此,您因主观意见而降低我的声誉并不是很好,因为有些人会不同意您的意见。请记住这里的要点,我只是提供了一种简单的方法来将其打印到 HTML 文件而不是 console.log()。
    • 请查看前两个链接,您可以在其中看到数百个不同意您的人。也有数百人同意你的观点,所以这不是一个明确的问题。您坚持自己的方式或高方式是相当封闭的,因为您无法确定是否有人会认为 document.write() 是满足他/她需求的最佳解决方案。
    【解决方案5】:

    对于当前年份,我们可以使用 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);

    【讨论】:

      【解决方案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>
        

        【讨论】:

        • 这是一个不必要的答案。
        • @crocsx 您可以将此代码添加到您的 HTML 中您想要显示的位置,而无需像所有其他答案一样在页脚或其他地方引用脚本
        • 同耶路撒冷程序员的回答略有不同
        • @Crocsx 这个答案更简洁不包括假设您使用引导程序的 HTML 元素和 CSS 类,它只有一行,对吗?
        • 问题只是在 JS 中获取年份,而不是获取年份并将其放在页脚中。在这种情况下,您可以编辑其他答案。无论如何...
        【解决方案8】:

        实例化类 Date 并调用其 getFullYear 方法以获取 yyyy 格式的当前年份。 像这样的:

        let currentYear = new Date().getFullYear();
        

        currentYear 变量将保存您正在寻找的值。

        【讨论】:

          【解决方案9】:

          一行JS代码就可以得到当前年份。

          &lt;p&gt;Copyright &lt;script&gt;document.write(new Date().getFullYear());&lt;/script&gt;&lt;/p&gt;

          【讨论】:

            【解决方案10】:

            TL;DR

            这里找到的大多数答案都是正确的大多数情况下,不能被认为是可靠的(因为它可能因机器而异)。

            可靠来源是:

            • Web 服务器的时钟(但请确保已更新)
            • 时间 API 和 CDN

            详情

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

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

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

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

            提到这一点的另一个来源是:JavaScript date and time object

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

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

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

            【讨论】:

              【解决方案11】:

              如果您将 ES6 Javascript 与 Angular、React、VueJS 等框架一起使用。然后您应该集成第三方实用程序库以方便您的项目。 DayJS 是最受欢迎的轻量级库之一,具有不可变数据结构。 在dayJS 中,您可以通过如下简单的一行代码获得year

              dayjs().year()
              

              还有很多有用的方法。所以我建议你在下一个项目中使用 dayjs。

              【讨论】:

                猜你喜欢
                • 2014-07-20
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-06-03
                • 1970-01-01
                相关资源
                最近更新 更多