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);
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.
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)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With