tl;dr
Year.now()
.getValue()
2023
java.time
The other Answers use the troublesome old date-time classes such as Calendar. These are supplanted by the java.time classes. For older versions of Android, see the ThreeTen-Backport and ThreeTenABP projects.
Year
class
Rather than pass around mere integers to represent a year, pass around objects. Namely, the Year
class.
Getting the current year requires a time zone. For any given moment, the date varies around the globe by zone. So it is possible for Pacific/Auckland
to be on 2018 while America/Montreal
is in 2017 simultaneously.
Better to pass explicitly the desired/expected zone. If omitted, you implicitly get the JVM’s current default time zone. That default can change at any moment during runtime, so it is not reliable.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
Year y = Year.now( z ) ;
When you do need an integer, extract the value.
int yearNumber = y.getValue() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?