[javascript] Shortest way to print current year in a website

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?

This question is related to javascript html date

The answer is


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();

It's not a good practice to use document.write. You can learn more about document.write by pressing here. Don't use document.write unless if you have to. Here's a somewhat friendly javascript/html solution. And yes, there is studies on how InnerHTML is bad, working on a more friendly soultion.

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

? javascript

? html

<span id="year"></span>

You can place the javascript code in your html, but it would look best in a javascript file. Very clean answer. Personally, I recommend writing the current year with PHP. Probably the safest answer.

If you want to write the current year with PHP, you can do so with this small code.

<?php echo date("Y"); ?>

Remember in order to apply this PHP code, your webpage file has to be PHP.


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();
        }
    })();
});

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.

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


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>
);
}

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!


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>

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:

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

In jQuery:

_x000D_
_x000D_
$(document).ready(function() {
  document.getElementById('copyright-year').appendChild(
    document.createTextNode(
      new Date().getFullYear()
    )
  );
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div> &copy; <span id="copyright-year"></span></div>
_x000D_
_x000D_
_x000D_


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

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>

_x000D_
_x000D_
<div>&copy;<script>document.write(new Date().getFullYear());</script>, Company._x000D_
</div>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?