How to get the current year as an integer in Scala

Scala FAQ: How do I get the current year as an integer (Int value) in Scala?

Solution: Use the Java 8 Year or LocalDate classes, or the older old Java Calendar class. The solutions are shown below.

Java 8 Year

import java.time.Year
val year = Year.now.getValue

Java 8 LocalDate

import java.time.LocalDate
val year = LocalDate.now.getYear

Java Calendar

If for some reason you’re not using Java 8 (or newer), here’s the older Calendar class solution:

import java.util.Calendar
val year = Calendar.getInstance.get(Calendar.YEAR)

REPL examples

Skipping over the import statements, here’s what the solutions look like in the Scala REPL:

scala> val year = Year.now.getValue
year: Int = 2018

scala> val year = LocalDate.now.getYear
year: Int = 2018

scala> val year = Calendar.getInstance.get(Calendar.YEAR)
year: Int = 2018

The java.time API

For more details, here are some statements from the java.time API page:

  • The (java.time API is the) main API for dates, times, instants, and durations.
  • The classes defined here represent the principle date-time concepts, including instants, durations, dates, times, time-zones and periods. They are based on the ISO calendar system, which is the de facto world calendar following the proleptic Gregorian rules. All the classes are immutable and thread-safe.
  • Each date-time instance is composed of fields that are conveniently made available by the APIs. For lower level access to the fields refer to the java.time.temporal package. Refer to the java.time.format package for customization options.
  • The java.time.chrono package contains the calendar neutral API ChronoLocalDate, ChronoLocalDateTime, ChronoZonedDateTime and Era. This is intended for use by applications that need to use localized calendars. The calendar neutral API should be reserved for interactions with users.

More information

For more reading, here are links to the Javadoc: