How to Set Current Year Copyright in JavaScript

Anika Tabassum Era Feb 02, 2024
  1. Use the getFullYear() Method for Current Year of Copyright in JavaScript
  2. Use the Regex and exec() Method for Current Year of Copyright in JavaScript
How to Set Current Year Copyright in JavaScript

In the development phase of a web app or similar tech product, it is not wise to manually set the copyright year every time.

Using JavaScript, it is easier to set a function or method to automatically change the date whenever it is updated.

Generally, the new Date() object returns the date according to the browser’s time zone. And the return format is a string.

The getFullYear() method simplifies the way of a reinitialization of years in every modification or change. This procedure makes a product more dynamic and reliable.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Test</title>
</head>
<body>
<script>document.write(new Date().getFullYear())</script>
</body>
</html>

Output:

Use getFullYear() Method for Current Year of Copyright

Whenever the Date() returns the value, it is in the string form and the initial start with the year.

We will generate a regex that will execute the first literals of the year. Here, we will use a regex to grab 4 characters and not calculate years after 9999.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
</head>
<body>
<script>document.write(/\d{4}/.exec(Date())[0])</script>
</body>
</html>

Output:

Use Regex and exec() Method for Current Year of Copyright

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Date