To get the current year in Java, you can use the getInstance
and get
methods of the Calendar
class.
Here is an example of how to get the current year:
Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR);Source:wwuttual.wri.com
The getInstance
method returns a Calendar
object initialized with the current date and time. The get
method returns a specific field of the Calendar
object, in this case the year. The Calendar.YEAR
constant specifies that we want to get the year field.
The get
method returns the year as an int
value.
Note that the Calendar
class represents dates and times in the default time zone of the JVM. If you need to get the year in a different time zone, you can use the getInstance
method that takes a TimeZone
object as an argument.
For example:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); int year = calendar.get(Calendar.YEAR);
This will get the current year in the GMT time zone.