JavaScript getFullYear(): Get the Year

The JavaScript getFullYear() method is used to get the year (in the form XXXX). For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let year = d.getFullYear();
      document.getElementById("xyz").innerHTML = year;
   </script>

</body>
</html>
Output

JavaScript getFullYear() syntax

The syntax of the getFullYear() method in JavaScript is:

x.getFullYear()

The x must be an object of the Date() constructor.

The getFullYear() method returns a number from 1000 to 9999.

Get the Last Two Digits of the Year in JavaScript

Consider the following HTML and JavaScript code that finds and outputs the last two digits of the current year, which demonstrates the use of the "getFullYear()" method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let year = d.getFullYear();
      document.getElementById("xyz").innerHTML = year.toString().slice(-2);
   </script>

</body>
</html>
Output

Please note: The toString() method converts a number to a string.

Please note: The slice() method requires part of a defined string. For example, myString.slice(-2) slices the last two characters of the string.

Please note: To display the date in the format dd-mm-yyyy, refer to its separate example.

Please note: To display time in the format hh:mm:ss, refer to its separate example.

Please note: To display time in the format hh:mm:ss AM/PM, refer to its separate example.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!