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


当前回答

抓住这个类,我们可以用javascript中的year替换它的textContent:document.querySelector(“.yr”).textContent=(new Date().getFullYear());&副本<span class=“yr”></span>公司。保留所有权利。

其他回答

您可以用一行JS代码获取当前年份。

<p>版权所有<script>document.write(newDate().getFullYear())</脚本></p>

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

var now=新日期()console.log(“当前时间为:”+now);//getFullYear函数将给出当前年份var currentYear=now.getFullYear()console.log(“当前年份为:”+currentYear);//getYear将为您提供1990年后的年份,即当前年份-1990年var year=now.getYear()console.log(“当前年份为:”+年);//getMonth提供月份值,但月份从0开始//加1得到实际月份值var month=now.getMonth()+1console.log(“当前月份为:”+月份);//getDate给出日期值var day=now.getDate()console.log(“今天是:”+day);

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

dayjs().year()

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

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

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

输出到HTML页面如下:

版权所有©2018

举个例子,你可以把它放在任何你想显示它的地方,而不需要引用页脚中的脚本或其他类似答案的地方

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

页脚上的版权说明作为示例

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