Shortest way to print current year in a website
Currently I’m using:
Is this as short as it gets?
Here’s the shortest I can get it:
That will work in all browsers I’ve run across.
How I got there:
- You can just call
getFullYeardirectly on the newly-created
Date, no need for a variable.
new Date().getFullYear()may look a bit odd, but it’s reliable: the
new Date()part is done first, then the
- You can drop the
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.
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>
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:
© Copyright 2017<script>new Date().getFullYear()>2017&&document.write("-"+new Date().getFullYear());</script>, Company.
© Copyright 2017-2018, Company.
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.
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.
The reason for this was the document.write actually wrote over the entire document.
I asked my friend to implement a server side solution and it worked for him.
The simple code in php
<?php echo date('Y'); ?>
Here’s the ultimate shortest most responsible version that even works both AD and BC.
That’s it. 6 Bytes shorter than the accepted answer.
If you need to be ES5 compatible, you can settle for: