How to Get the Current Year in JavaScript


How can we get the current year in JavaScript?

Get current year

We can get the current year using the Date object and its getFullYear() method.

new Date().getFullYear();

Aside from getFullYear(), we have many other useful Date methods available to us.

new Date().getDate()         // Day: number (1-31)
new Date().getDay()          // Weekday: number (0-6)
new Date().getFullYear()     // Year: 4 digits (yyyy)
new Date().getHours()        // Hour (0-23)
new Date().getMilliseconds() // Milliseconds (0-999)
new Date().getMinutes()      // Minutes (0-59)
new Date().getMonth()        // Month (0-11)
new Date().getSeconds()      // Seconds (0-59)
new Date().getTime()         // Time (milliseconds since January 1, 1970)

This is commonly used in the footer of many websites.

We can write the year directly into the DOM.

<p>Copyright <script>document.write(new Date().getFullYear());</script></p>

Similarly, we can target a specific element and insert the year into the HTML.

<p>Copyright <span id="year"></span></p>
<script>
  document.getElementById('year').innerHTML = new Date().getFullYear();
</script>