TL; DR
Year.now() .getValue()
java.time
Other answers use nasty old time classes such as Calendar. They are superseded by java.time classes. For older versions of Android, see ThreeTen-Backport and ThreeTenABP Projects.
Year class
Instead of passing only integers to represent the year, go around objects. Namely, the Year class.
To obtain the current year, a time zone is required. At any given moment, the date changes around the world by zone. Thus, it is possible that Pacific/Auckland will be in 2018, and America/Montreal - in 2017 at the same time.
It is better to explicitly convey the desired / expected zone. If you did not specify, you implicitly get the current JVM time zone. This default value can change at any time during runtime, so it is not reliable.
ZoneId z = ZoneId.now( "Asia/Kolkata" ) ; Year y = Year.now( z ) ;
When you 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 supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .
The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .
Where to get java.time classes?
- Java SE 8 , Java SE 9 , and then
- Built in.
- Part of the standard Java API with integrated implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the functionality of java.time is ported back to Java 6 and 7 in ThreeTen-Backport .
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) specifically for Android.
- See How to use ThreeTenABP ....
Basil bourque
source share