Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying the last two digits of the current year in Java

Tags:

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); 
like image 833
нαƒєєz Avatar asked Nov 19 '13 11:11

нαƒєєz


People also ask

How to get last 2 digits of year in Java?

Using Modulo Arithmetic Operator: We can use the modulo operator (%) to extract the last two digits by taking the modulo of the year by 100.

How do you write the last two digits of a year?

According to this source the correct symbol to abbreviate year using two digits is an apostrophe: When abbreviating a year, remove the first two numbers and indicate the omission by using an apostrophe: 2009 becomes '09 (not '09) 2010 becomes '10 (not '10)

How to get last 2 digits of integer in Java?

To get the last 2 digits of a number:Convert the number to a string. Call the slice() method on the string, passing it -2 as a parameter. The slice method will return the last 2 characters in the string.

How do you find the last two digits of a number?

Last two digits of a number is basically the tens place and units place digit of that number. So given a number say 1439, the last two digits of this number are 3 and 9, which is pretty straight forward.


2 Answers

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.

like image 185
Robin Krahl Avatar answered Sep 29 '22 07:09

Robin Krahl


You can use a SimpleDateFormat to format a date as per your requirements.

DateFormat df = new SimpleDateFormat("yy"); // Just the year, with 2 digits String formattedDate = df.format(Calendar.getInstance().getTime()); System.out.println(formattedDate); 

Edit: Depending on the needs/requirements, either the approach suggested by me or the one suggested by Robin can be used. Ideally, when dealing with a lot of manipulations with the Date, it is better to use a DateFormat approach.

like image 21
Rahul Avatar answered Sep 29 '22 06:09

Rahul