Explain Codes LogoExplain Codes Logo

Get integer value of the current year in Java

java
time-pitfalls
java-8
best-practices
Alex KataevbyAlex Kataev·Sep 3, 2024
TLDR

Join the 2023 club with just one line of Java code where you can get the current year:

int currentYear = java.time.Year.now().getValue();

This simple line of code gets the year from the current date and extracts it as an int.

Java time pitfalls and tricks

Dealing with time zones

Remember, time zones can be tricky! They’ve bamboozled many programmers and caused numerous bugs. When you invoke Year.now(), it defaults to the machine's time zone. So, to ensure the correct year, remember to specify the time zone:

import java.time.ZoneId; int currentYear = Year.now(ZoneId.of("UTC")).getValue(); // Always know where you're standing… in time.

Living in the past: Java 7 and before

Got some dinosaur code out there? Don’t worry! If you're keeping the legacy alive using Java 7 or lower, just pull from the Calendar to fetch the current year:

int currentYear = Calendar.getInstance().get(Calendar.YEAR); // This line once caught a T-Rex!

Breaking up with java.util.Date

The java.util.Date isn’t just old, it’s Jurassic. With its issues like mutable state, tremble-inducing timezone support, and more, it’s a nightmare best avoided. Instead, embrace the shiny and new java.time package:

int currentYear = java.time.Year.now().getValue(); // Welcome to the future!

Digging deeper

Be prepared: Handling exceptions

Your ship should never sink. Sail smoothly by handling potential exceptions. Here's how to catch a random DateTimeException:

try { int currentYear = Year.now().getValue(); } catch (DateTimeException e) { e.printStackTrace(); // Shoutout to console logs, the unsung heroes. }

Time travelling: Testing with a fixed clock

In the world of unit tests, we are all time travellers. Use Clock.fixed() to simulate a specific year:

import java.time.Clock; import java.time.LocalDate; import java.time.Month; import java.time.Year; import java.time.ZoneId; Clock fixedClock = Clock.fixed(LocalDate.of(2025, Month.JANUARY, 1).atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault()); int testYear = Year.now(fixedClock).getValue(); // And voila! It's always 2025 in this corner of the codebase.

System properties: An extra layer of validation

Looking for a sanity check? You can cross-reference the year obtained with the system property for the current year:

int currentYear = Year.now().getValue(); int systemYear = Integer.parseInt(System.getProperty("user.year", String.valueOf(currentYear))); assert currentYear == systemYear; // Because two pairs of eyes are always better than one.