Shortest way to print current year in a website
Asked Answered
R

20

323

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.

Currently I’m using:

<script type="text/javascript">var year = new Date();document.write(year.getFullYear());</script>

Is this as short as it gets?

Rhodie answered 30/12, 2010 at 12:29 Comment(1)
Just so you know, it's generally not recommended to use document.write, as it has several gotchas that can catch you by surprise. More information on the MDN article on document.write.Electrolyze
B
735

Years later, when doing something else I was reminded that Date() (without new) returns a string, and a way that's one character shorter that my original below came to me:

<script>document.write(/\d{4}/.exec(Date())[0])</script>

The first sequence of four digits in the string from Date() is specified to be the year. (That wasn't specified behavior — though it was common — when my original answer below was posted.)

Of course, this solution is only valid for another 7,979 years (as of this writing in 2021), since as of the year 10000 it'll show "1000" instead of "10000".


You've asked for a JavaScript solution, so 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-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 .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 despise and rail against, but in this specific use case it should be safe enough.

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


However, unless you're using a server that can only provide static files, you're probably better off doing this on the server with a templating engine and using caching headers to allow the resulting page to be cached until the date needs to change. That way, you don't require JavaScript on the client. Using a non-defer/async script tag in the content also briefly delays the parsing and presentation of the page (for exactly this reason: because the code in the script might use document.write to output HTML).

Bolanger answered 30/12, 2010 at 12:32 Comment(3)
@SystemsRebooter - You can only use document.write for inline content during the initial parsing phase (as shown above, in a <script>...</script> tag -- or in a .js file loaded with a script tag without defer or async). When the page is fully parsed, the document stream is closed, and using document.write reopens it -- completely replacing the document with a new one. If you want to add a year after the main parsing is complete, you want to use the DOM. (This isn't a change, it's always been this way.)Bolanger
Note that in 2020 the answer is really "use a template engine that has a CLI processor and put a template tag in your files". Document.write still made sense 10 years ago, these days it's best left to the annals of history.Lagomorph
@Mike'Pomax'Kamermans - I think that was probably the best answer to the title of the question even 10 years ago. ;-) I think I used to have a comment on the question saying that, but comments are ephemeral (and I could be wrong). The body of the question specifically asks for JavaScript, but I should have (and have, now) said what you said in the answer. Thanks!Bolanger
B
74

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>
    &copy;
    <span id="copyright">
        <script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
    </span>
    Company Name
</div>
Beckham answered 17/9, 2015 at 19:2 Comment(3)
Yes - a good solution! I recommend to move the script snippet right before the closing body tag or to your other js at the end of the html body.Lysine
createTextNode() does not interpret html like <br> how do you create a node with HTML?Mei
This should be the best solution if you are aware of the consequences of using document.write.Scarlett
U
41

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:

&copy; 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:

&copy; Copyright 2010-<script>document.write(new Date().getFullYear())</script>, Company.
Ureide answered 20/8, 2014 at 22:7 Comment(0)
S
21

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

Enjoy!

Selfcontent answered 25/3, 2015 at 6:37 Comment(6)
Your solution is so simple, But the thing is that the question is related to JavaScriptDichasium
Haha! The solution was already given when I posted this. Still I wanted people to know there are other ways also! Hope it helps someone like me in the future!Selfcontent
I do agree with you that we need to look alternative when there is no solution with the same thinking. Be careful about down vote 😉Dichasium
And what if the server-side solution is Node.js and thus JavaScript?Pylon
@Pylon - It won't work! Someone did warn me about a negative rating! As I said, the solution was already given when I posted this...Selfcontent
If the page goes blank, this means that document.write was used after the DOM already loaded. The solution is to not use document.write after all the DOM loads, or, even better, not to use document.write at all.Pompea
B
20
<script type="text/javascript">document.write(new Date().getFullYear());</script>
Bayles answered 30/12, 2010 at 12:35 Comment(1)
I know just <script> is shorter (see other answer), but his is more current and will always work. In fact, I had an instance in WP where the other one wouldn't work, but this one was no problem. Not sure why WP would throw an issue over this...I know nowadays you can drop the ; at the end and the script default to js anyway, but still.Nibbs
G
17

Here's the ultimate shortest most responsible version that even works both AD and BC.

[drum rolls...]

<script>document.write(Date().split` `[3])</script>

That's it. 6 Bytes shorter than the accepted answer.

If you need to be ES5 compatible, you can settle for:

<script>document.write(Date().split(' ')[3])</script>
Gorge answered 22/8, 2016 at 19:45 Comment(2)
What about if your user goes back in time to before 1000 AD? Or what if a user is using your app > 9999 AD? #responsibleCode #NotAnotherY2K ;)Preparation
@NickSteele Hopefully we aren't writing pure javascript at that point.Astrogation
B
12

It's not a good practice to use document.write. You can learn more about document.write by pressing here. Here's a somewhat friendly JavaScript solution. And yes, there are studies on how InnerHTML is bad, working on a more friendly solution.

document.getElementById("year").innerHTML = (new Date().getFullYear());

↑ JavaScript

↓ HTML

<p>Company &copy; <span id="year"></span> All Rights Reserved.</p>

Here's a JSFiddle to test it out. Instead of using JavaScript, personally, I'd recommend writing the current year with PHP, it's a lot more safe doing with PHP instead of JavaScript.

<?php echo date("Y"); ?>
Biphenyl answered 26/12, 2020 at 7:18 Comment(0)
A
6

<div>&copy;<script>document.write(new Date().getFullYear());</script>, Company.
</div>
Aldus answered 27/9, 2019 at 16:54 Comment(0)
B
5

For React.js, the following is what worked for me in the footer...

render() {
    const yearNow = new Date().getFullYear();
    return (
    <div className="copyright">&copy; Company 2015-{yearNow}</div>
);
}
Berget answered 5/1, 2020 at 2:28 Comment(0)
P
5

Easy-peasy!

<p>&copy;
  <script type="text/javascript">
    document.write(new Date().getFullYear());
  </script>
</p>
Printery answered 14/8, 2022 at 0:5 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Psychosomatic
S
3

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

so solution without errors is:

(new Date).getFullYear();
Saintebeuve answered 27/4, 2020 at 19:35 Comment(1)
what is solution here ?Cordate
M
3

The Accepted Answer Does Not Always Work

A recent update has caused all of my WordPress footer copyright dates to get pushed down to then end of the page instead of writing it inline like it used to. I'm sure there are other cases where this may happen as well, but this is just where I've noticed it.

enter image description here

If this happens, you can fix it by creating an empty span tag and injecting your date into it like this:

<span id="cdate"></span><script>document.getElementById("cdate").innerHTML = (new Date().getFullYear());</script> 

or if you have jquery enabled on your site, you can go a bit more simple like this:

<span id="cdate"></span><script>$("#cdate").html(new Date().getFullYear());</script> 

This is similar to Adam Milecki's answer but much shorter

Mortician answered 11/11, 2020 at 20:26 Comment(0)
L
3

Full year:

document.getElementById("getyear").innerHTML = (new Date().getFullYear());
<span id="getyear"></span>
Lydgate answered 15/7, 2021 at 22:46 Comment(0)
G
2

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.

//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();
        }
    })();
});
Gadhelic answered 6/7, 2019 at 6:9 Comment(0)
W
1

There are many solutions to this problem as provided by above experts. Below solution can be use which will not block the page rendering or not even re-trigger it.

In Pure Javascript:

window.addEventListener('load', (
    function () {
        document.getElementById('copyright-year').appendChild(
            document.createTextNode(
                new Date().getFullYear()
            )
        );
    }
));
<div> &copy; <span id="copyright-year"></span></div>

In jQuery:

$(document).ready(function() {
  document.getElementById('copyright-year').appendChild(
    document.createTextNode(
      new Date().getFullYear()
    )
  );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> &copy; <span id="copyright-year"></span></div>
Weak answered 14/10, 2020 at 7:50 Comment(0)
F
1

This answer is similar to Ray's but uses a template literal and text fallback

<p>&copy;
  <span id="copyright-year">2021</span>
  Company Name
</p>

<script>
  document.getElementById("copyright-year").innerHTML = `${new Date().getFullYear()}`;
</script>

Results in © 2022 Company Name

document.getElementById("copyright-year").innerText = `${new Date().getFullYear()}`;

also works.

Fustian answered 6/11, 2022 at 7:1 Comment(0)
C
0

If you need the current year multiple times on your site you can do this:

document.querySelectorAll("copy-year").forEach(el => {
    el.textContent = `${el.textContent} - ${new Date().getFullYear()}`;
});
Copyright Company <copy-year>1234</copy-year> ©

I know, it is not the shortest way, but it works really good.

PS: You need to have JS on bottom of your page or use defer attribute on script tag.

Caterinacatering answered 12/4, 2021 at 18:13 Comment(0)
F
0

For React.js, We can use in a single line-

    return 
    <div className="copyright">Company 2015-{new Date().getFullYear()}</div>
    
Flite answered 17/9, 2021 at 12:50 Comment(0)
C
0

This snippet kicks in once the HTML document finishes parsing. Its job is to tweak elements that have the .dyn_year class, especially in cases where a single line of text may encompass multiple copyright years.

Script:

<script>document.addEventListener("DOMContentLoaded",()=>{ document.querySelectorAll(".dyn_year").forEach(el=>el.innerText=new Date().getFullYear()); })</script>

HTML:

<span> © 2014-<span class="dyn_year"></span>  LoremIpsum, LLC. All rights reserved. Lipsum® and Gipsum® are trademarks of LoremIpsum, LLC. EmlorSumip is a tradename of LoremIpsum, LLC. © 2001-<span class="dyn_year"></span> GoremGipsum LLC. LipGipSum®  is a trademark of GoremGipsum LLC.</span>

DOMContentLoaded:

https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event https://caniuse.com/?search=DOMContentLoaded

querySelectorAll:

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll https://caniuse.com/?search=queryselectorall

Coopery answered 24/11, 2023 at 6:23 Comment(0)
M
-2

Shortest way to print current year in a website

Just use this code

<?php echo date('Y'); ?>
Met answered 30/10, 2022 at 14:38 Comment(1)
This answer is related to PHP when the OP specifically asks about how to do this using JavaScript in static HTML.Philanthropy

© 2022 - 2024 — McMap. All rights reserved.