In this blog post, we will learn how to display the current year in HTML using JavaScript. HTML alone does not have the ability to fetch the current year, so we will use JavaScript to achieve this functionality.
Using JavaScript to Get Current Year
JavaScript provides us with the Date() object to get the current date and time. To display the current year, we can create a new instance of the Date() object and then use the getFullYear() method to get the current year.
Here’s an example of how to use JavaScript to display the current year in an HTML element:
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display Current Year</title> <h1>Current Year:</h1> <span id="currentYear"></span> <script> // Create a new Date object const currentDate = new Date(); // Get the current year const currentYear = currentDate.getFullYear(); // Display the current year in the HTML element with id "currentYear" document.getElementById("currentYear").innerText = currentYear; </script>
In this example, we first create a new Date() object and store it in the currentDate variable. Then, we use the getFullYear() method to get the current year and store it in the currentYear variable. Finally, we use document.getElementById() to get the HTML element with the id “currentYear” and set its innerText to the value of currentYear.
Conclusion
Although HTML cannot directly fetch the current year, using JavaScript in conjunction with HTML allows us to easily display the current year on our web pages. By utilizing the Date() object and its getFullYear() method, we can quickly and efficiently achieve this functionality.