Get the current Year for Copyright using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 28, 2022

banner

Photo from Unsplash

Get the current Year for Copyright using JavaScript #

Use the getFullYear() method to get the current year for copyright, e.g. new Date().getFullYear(). The getFullYear method returns the current year when called on the current date.

index.js
const currentYear = new Date().getFullYear(); console.log(currentYear); // 👉️ 2022

Here is an example that injects the current year into an HTML element directly on the page.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>Content here</div> <div id="copyright"></div> <script> const paragraph = ` <p> Copyright &copy; ${new Date().getFullYear()} John Doe </p> `; document.getElementById('copyright').innerHTML = paragraph; </script> </body> </html>

And here is an example that displays the current date for copyright in a React.js component using JSX.

footer.tsx
export const Footer = () => ( <div> <p> Copyright &copy; {new Date().getFullYear()} John Doe </p> </div> );

The Date() constructor creates a new Date object.

We didn't pass any parameters to the constructor when creating the Date, so it created a Date object that stores the current date.

The getFullYear method returns a number that represents the year of the given date.

If you add the code snippet that uses HTML, make sure to place the script tag at the bottom of the body tag, after all of the DOM elements have been declared.

Placing the script tag before declaring the DOM elements would run it before the elements exist on the page and cause an error.

In the HTML example, we used the innerHTML property to set the inner html of the element with id set to copyright.

The paragraph variable uses backticks (not single quotes) to create a template string that stores a p element that contains the copyright message.

Here is how the p element looks on the page.

current year for copyright

My blog uses the same approach to display the current year at the footer.

You could change the structure or the style of the element by editing the html code in the template string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.