Javascript 在网站中打印当前年份的最短方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4562587/
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
Shortest way to print current year in a website
提问by tpow
I need to update a few hundred static HTML pages that have the copyright date hard coded in the footer. I want to replace it with some JavaScript that will automatically update each year.
我需要更新几百个在页脚中硬编码版权日期的静态 HTML 页面。我想用一些每年都会自动更新的 JavaScript 替换它。
Currently I'm using:
目前我正在使用:
<script type="text/javascript">var year = new Date();document.write(year.getFullYear());</script>
Is this as short as it gets?
这是尽可能短吗?
回答by T.J. Crowder
Here's the shortest I can get it:
这是我能得到的最短的:
<script>document.write(new Date().getFullYear())</script>
That will work in all browsers I've run across.
这将适用于我遇到的所有浏览器。
How I got there:
我是如何到达那里的:
- You can just call
getFullYear
directly on the newly-createdDate
, no need for a variable.new Date().getFullYear()
may look a bit odd, but it's reliable: thenew Date()
part is done first, then the.getFullYear()
. - You can drop the
type
, because JavaScript is the default; this is even documented as part of the HTML5 specification, which is likely in this case to be writing up what browsers already do. - You can drop the semicolon at the end for one extra saved character, because JavaScript has "automatic semicolon insertion," a feature I normally despiseand rail against, but in this specific use case it should be safe enough.
- 您可以直接调用
getFullYear
新创建的Date
,不需要变量。new Date().getFullYear()
可能看起来有点奇怪,但它是可靠的:new Date()
首先完成部分,然后是.getFullYear()
. - 您可以删除
type
,因为 JavaScript 是默认值;这甚至被记录为HTML5 规范的一部分,在这种情况下很可能是在写浏览器已经做的事情。 - 您可以在末尾删除分号以节省一个额外的字符,因为 JavaScript 具有“自动分号插入”功能,这是我通常鄙视和反对的功能,但在这个特定用例中,它应该足够安全。
It's important to note that this only works on browsers where JavaScript is enabled. Ideally, this would be better handled as an offline batch job (sed
script on *nix, etc.) once a year, but if you want the JavaScript solution, I think that's as short as it gets. (Now I've gone and tempted fate.)
需要注意的是,这只适用于启用了 JavaScript 的浏览器。理想情况下,这最好作为sed
一年一次的离线批处理作业(*nix 上的脚本等)来处理,但是如果您想要 JavaScript 解决方案,我认为它会尽可能短。(现在我已经去试探命运了。)
回答by Adam Milecki
TJ's answer is excellent but I ran into one scenario where my HTML was already rendered and the document.write script would overwrite all of the page contents with just the date year.
TJ 的回答非常好,但我遇到了一个场景,我的 HTML 已经呈现,并且 document.write 脚本将仅用日期年份覆盖所有页面内容。
For this scenario, you can append a text node to the existing element using the following code:
对于这种情况,您可以使用以下代码将文本节点附加到现有元素:
<div>
©
<span id="copyright">
<script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
</span>
Company Name
</div>
回答by Martin Adams
If you want to include a time frame in the future, with the current year (e.g. 2017) as the start year so that next year it'll appear like this: “? 2017-2018, Company.”, then use the following code. It'll automatically update each year:
如果您想在未来包含一个时间范围,则以当前年份(例如 2017 年)作为开始年份,以便明年显示如下:“?2017-2018,公司。”,然后使用以下代码。它将每年自动更新:
© Copyright 2017<script>new Date().getFullYear()>2017&&document.write("-"+new Date().getFullYear());</script>, Company.
? Copyright 2017-2018, Company.
? 版权所有 2017-2018,公司。
But if the first year has already passed, the shortest code can be written like this:
但是如果第一年已经过了,那么最短的代码可以这样写:
© Copyright 2010-<script>document.write(new Date().getFullYear())</script>, Company.
回答by Thomas Kremmel
<script type="text/javascript">document.write(new Date().getFullYear());</script>
回答by Arcanyx
The JS solution works great but I would advise on a server side solution. Some of the sites I checked had this issue of the entire page going blank and only the year being seen once in a while.
JS 解决方案效果很好,但我会建议服务器端解决方案。我查过的一些网站有这个问题,即整个页面都变成空白,并且只偶尔看到一年。
The reason for this was the document.writeactually wrote over the entire document.
这样做的原因是document.write实际上写了整个文档。
I asked my friend to implement a server side solution and it worked for him. The simple code in php
我让我的朋友实现一个服务器端解决方案,它对他有用。php中的简单代码
<?php echo date('Y'); ?>
Enjoy!
享受!
回答by Christiaan Westerbeek
Here's the ultimate shortest most responsible version that even works both AD and BC.
这是最终最短最负责任的版本,它甚至适用于 AD 和 BC。
[drum rolls...]
[鼓卷...]
<script>document.write(Date().split` `[3])</script>
That's it. 6 Bytes shorter than the accepted answer.
就是这样。比接受的答案短 6 个字节。
If you need to be ES5 compatible, you can settle for:
如果你需要兼容 ES5,你可以满足:
<script>document.write(Date().split(' ')[3])</script>
回答by Chris
This is the best solution I can think of that will work with pure JavaScript. You will also be able to style the element as it can be targeted in CSS. Just add in place of the year and it will automatically be updated.
这是我能想到的最好的解决方案,它适用于纯 JavaScript。您还可以设置元素的样式,因为它可以在 CSS 中定位。只需添加代替年份,它就会自动更新。
//Wait for everything to load first
window.addEventListener('load', () => {
//Wrap code in IIFE
(function() {
//If your page has an element with ID of auto-year-update the element will be populated with the current year.
var date = new Date();
if (document.querySelector("#auto-year-update") !== null) {
document.querySelector("#auto-year-update").innerText = date.getFullYear();
}
})();
});
回答by Jonathan Akwetey Okine
<div>©<script>document.write(new Date().getFullYear());</script>, Company.
</div>
回答by Kris Stern
For React.js, the following is what worked for me in the footer...
对于 React.js,以下是页脚中对我有用的内容...
render() {
const yearNow = new Date().getFullYear();
return (
<div className="copyright">© Company 2015-{yearNow}</div>
);
}
回答by Karol
according to chrome audit
根据铬审计
For users on slow connections, external scripts dynamically injected via
document.write()
can delay page load by tens of seconds.https://web.dev/no-document-write/?utm_source=lighthouse&utm_medium=devtools
对于连接速度较慢的用户,通过动态注入的外部脚本可以将
document.write()
页面加载延迟数十秒。https://web.dev/no-document-write/?utm_source=lighthouse&utm_medium=devtools
so solution without errors is:
所以没有错误的解决方案是:
(new Date).getFullYear();