This is a one-liner:
System.out.println(Year.now().format(DateTimeFormatter.ofPattern("uu")));
I am using java.time.Year
, one of a number of date and time classes introduced in Java 8 (and also backported to Java 6 and 7). This is just one little example out of very many where the new classes are more convenient and lead to clearer code than the old classes Calendar
and SimpleDateFormat
.
If you just wanted the two-digit number, not as a string, you may use:
Year.now().getValue() % 100
.
The other answers were good answers in 2013, but the years have moved on. :-)
Edit: New Year doesn’t happen at the same time in all time zones. To make the dependency on time zone clear in the code I would usually write Year.now(myDesiredTimeZoneId)
, for example in the form Year.now(ZoneId.systemDefault())
.