JavaScript get current year denotes how we can extract the year part from a given date. However, a JS Date object provides us a list of methods to get different pieces of information from it. But, our focus is to get the only year part from a date.
Table of Contents
If we are working with a date object in JavaScript, the most common task is to retrieve the current year. Understanding how to retrieve various components of a Date object in JavaScript is crucial, regardless of whether you are developing an application, a website, or simply finishing a JS project for school. I will try my best to provide you some answers in my blog post along with code explanations so that you can apply my approaches directly to your projects.
Getting the Current Year Using JavaScript
#1: Using Date() Object
The most popular way to get the current year from a date in JavaScript is by using the built-in Date() object. The Date() object has many useful methods to extract different parts of a date, including the year. Let’s check the Date() object first:
<script>
// Create a Date Object and
// Extract the year
const currentYear = new Date().getFullYear();
// Display the Current Year
console.log(currentYear); // Output: 2024 (or the current year)
</script>
Code Explanation
- new Date() creates a new date object with the current date and time.
- .getFullYear() returns the four-digit year from the date object.
This method is very simple and a commonly used method for getting the current year.
Convert into a Custom Function
You can create a custom function by wrapping the logic inside a function. So that you can use this method repeatedly.
<script>
// javascript get current year custom function
function getCurrentYear(myDate) {
return myDate.getFullYear();
}
console.log(getCurrentYear(new Date())); // Output: 2024
</script>
#2: JavaScript Get Current Year – A Complete Example
Let’s combine all together to implement JavaScript get current year in a single code block. Here is a complete example that enables us to get the current year from a date and display it on a web page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Get Current Year</title>
</head>
<body>
<div style="min-height: 100px;">
<span style="font-size: large;font-weight: bold;color: blue;">
Learn JavaScript from Coderstechzone.com
</span>
</div>
<footer>
<p>© <span id="year"></span> coderstechzone.com | All rights reserved.</p>
</footer>
<script>
// Step 1: Create a Date object
const today = new Date();
// Step 2: Get the current year
const currentYear = today.getFullYear();
// Step 3: Display the current year on the web page
document.getElementById("year").textContent = currentYear;
</script>
</body>
</html>
Output
Code explanation
In this example:
- The JavaScript code gets the current year.
- The HTML code contains a <span> element with the id of “year”.
- The JavaScript code updates the text content of the <span> element to display the current year.
If you run this example JS code in your browser, you will see the current year in the footer section of the web page.
#3: Using Intl.DateTimeFormat()
JavaScript get current year using the Intl.DateTimeFormat() object. This method is more robust and allows us for easy formatting of dates for different locales.
<script>
const formatter = new Intl.DateTimeFormat('en', { year: 'numeric' });
const currentYear = formatter.format(new Date());
console.log(currentYear); // Output: 2024
</script>
Advantages
- Localization: This method is ideal for formatting dates according to specific locales.
- Flexibility: You can format other parts of the date, not just the year.
Comparison of Methods to Get the Current Year
Method | Code Example | Advantages | Use Case |
---|---|---|---|
Date().getFullYear() | new Date().getFullYear(); | Simple and widely used | Basic year retrieval |
Intl.DateTimeFormat() | new Intl.DateTimeFormat(‘en’, { year: ‘numeric’ }).format(new Date()); | Good for localization | International date formatting |
More About the Date Object
The Date object in JavaScript is very powerful and a bit complicated. You can do a lot more things with the Date object than just getting the current year. Here is a list of some other useful date methods that you apply in your code:
There are two groups of date methods available in JavaScript. One is local, and another one is UTC. I am listing both popular methods below for your future use. So bookmark this page now.
Date Parts | Local Getter Setter | UTC Getter Setter | Remarks | ||
Get | Set | Get | Set | ||
Year | getFullYear() | setFullYear() | getUTCFullYear() | setUTCFullYear() | Between the years 1000 and 9999 |
Month | getMonth() | setMonth() | getUTCMonth() | setUTCMonth() | Returns the current month (0-11). Note that January is 0 and December is 11. |
Date | getDate() | setDate() | getUTCDate() | setUTCDate() | Returns the current day of the month (1-31) |
Hours | getHours() | setHours() | getUTCHours() | setUTCHours() | Returns the current hour (0-23) |
Minutes | getMinutes() | setMinutes() | getUTCMinutes() | setUTCMinutes() | Returns the current minute (0-59) |
Seconds | getSeconds() | setSeconds() | getUTCSeconds() | setUTCSeconds() | Returns the current second (0-59) |
Milliseconds | getMilliseconds() | setMilliseconds() | getUTCMilliseconds() | setUTCMilliseconds() | |
Day of Week | getDay() | N/A | getUTCDay() | N/A | Returns the current day of the week (0-6). Note that Sunday is 0 and Saturday is 6 |
Example: Displaying the Full Date
Here is a quick example that shows how to display the full date in your required format:
<script>
const today = new Date();
const day = today.getDate();
// Months are zero-based, so we add 1
const month = today.getMonth() + 1;
// javascript get current year
const year = today.getFullYear();
const fullDate = `${month}/${day}/${year}`;
console.log(fullDate); // Like 8/24/2024
</script>
Handling Time Zones
Always keep in mind when working with dates in JavaScript that the Date object is sensitive by the user time zone. It means that if anyone from a different time zone runs your code, he will definitely get a different date or time. Here is a quick example that shows how to display the full date in your required format:
Using UTC Methods
If you want that your dates and times are not affected by time zones, use the UTC methods of the Date object. I have already listed all methods in the above table. These methods work with Coordinated Universal Time (UTC), which is equivalent to everywhere in the world.
For example, to get the current year in UTC, you can use the getUTCFullYear() method:
<script>
const today = new Date();
// javascript get current year - UTC method
const currentYearUTC = today.getUTCFullYear();
console.log(currentYearUTC);
</script>
This will give you the current year in UTC.
Common Use Cases for the Current Year
JavaScript get current year – Now you know everything about it. let’s look at some common use cases:
Calculating Age
If you have a birth year and want to calculate a person’s age, you can subtract the birth year from the current year easily with this below code example.
<script>
const birthYear = 1990;
// JavaScript Get Current Year
const currentYear = new Date().getFullYear();
const age = currentYear - birthYear;
console.log(`You are ${age} years old.`);
</script>
This code will calculate the age based on the current year.
Validating Dates
When working with dates in forms or databases, you might need to validate that a year is within a certain range. For example, you can check that a year is not in the future. If so, restrict it.
<script>
const inputYear = 2025;
// JavaScript Get Current Year
const currentYear = new Date().getFullYear();
if (inputYear > currentYear) {
console.log("The year cannot be in the future.");
} else {
console.log("The year is valid.");
}
</script>
Output
This simple validation ensures that the input year is not greater than the current year.
Using the Year in a URL
<script>
// JavaScript Get Current Year
const currentYear = new Date().getFullYear();
const url = `https://coderstechzone.com/javascript/${currentYear}`;
console.log(url);
// Output: https://coderstechzone.com/javascript/2024
</script>
This is very useful to fetch year specific data.
Best Practices for Using the Current Year in JavaScript
When working with dates in JavaScript, especially the current year, you can follow these best practices:
- Use Functions for Reusability: Create a custom function that allows you to easily reuse it throughout your code. Follow the above examples.
- Consider Timezones: Note that JavaScript always uses the local timezone of the user’s browser. If your application requires a specific timezone, make sure to adjust the logic accordingly.
- Update Dynamic Dates Automatically: If you are using the current year for display purposes, such as in a footer, ensure that your JavaScript runs every time the page loads to keep the date updated.
Conclusion
JavaScript get current year is straightforward with the built-in Date() object and other methods like Intl.DateTimeFormat(). Whether you are dynamically displaying the year in your website’s footer, performing age calculations, or using it in a URL, JavaScript gives us several methods to fulfill our needs.
To summarize:
- Use new Date().getFullYear() for simple and effective retrieval of the current year.
- Use a custom function to make your code more maintainable.
- Consider using Intl.DateTimeFormat() if you need to implement localization features.
By following the techniques that I have shown in this post, you are now good enough to handle date-related different parts and ensure your website or application always reflects the correct year.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply