Displaying the last two digits of the current year in Java

нαƒєєz picture нαƒєєz · Nov 19, 2013 · Viewed 46.7k times · Source

How can I display only the last two digits of the current year without using any substring algorithms or any third party libraries?

I have tried the below method and it gave a four-digit year. I want to know whether there are any date formatting options available to get the current year in two-digit format.

Calendar.getInstance().get(Calendar.YEAR);

Answer

Robin Krahl picture Robin Krahl · Nov 19, 2013

You can simply use the modulo operator:

int lastTwoDigits = Calendar.getInstance().get(Calendar.YEAR) % 100;

Edit: Using a SimpleDateFormat, as @R.J proposed, is the better solution if you want the result to be a string. If you need an integer, use modulo.