How to Create an Automatic Current Year in JavaScript
Back to Articles
JavascriptFebruary 26, 20265 min read

How to Create an Automatic Current Year in JavaScript

A

APKEY Team

Editor

Learn how to automatically display the current year using JavaScript. This beginner-friendly tutorial explains simple methods to generate a dynamic year for your website footer with practical code examples.

Keeping your website updated is important for professionalism and credibility. One small but essential detail is the copyright year in your footer. Instead of updating it manually every year, you can use JavaScript to generate the current year automatically.

In this tutorial, you’ll learn how to create an automatic year using JavaScript with simple and clean code.

Why Use an Automatic Year?

Using JavaScript to generate the year offers several advantages:

  • No need for manual updates every year
  • Prevents outdated copyright information
  • Saves time and reduces maintenance
  • Improves website professionalism

Step 1: Basic JavaScript Method

JavaScript provides a built-in Date object that allows you to retrieve the current year easily.

Here’s the simplest method:

<script>
  const currentYear = new Date().getFullYear();
  document.write(currentYear);
</script>

How It Works:

  • new Date() creates a new date object.
  • .getFullYear() extracts the current year (e.g., 2026).
  • document.write() prints it directly to the page.

⚠️ However, document.write() is not recommended for modern websites.

Step 2: Recommended Modern Method (Best Practice)

A better approach is to insert the year into a specific HTML element.

HTML

<footer>
  <p>&copy; <span id="year"></span> Your Company. All rights reserved.</p>
</footer>

<script>
  document.getElementById("year").textContent = new Date().getFullYear();
</script>

Why This Method Is Better

  • Cleaner code
  • Works well with modern frameworks
  • Does not overwrite your document
  • Easy to maintain

Step 3: Using JavaScript in an External File

For better organization, place your script inside a separate file.

index.html

<footer>
  <p>&copy; <span id="year"></span> Your Company. All rights reserved.</p>
</footer>
<script src="script.js"></script>

#js#javascript