Displaying the last two digits of the current year in Java

date-formatting, gregorian-calendar, java

Solution

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.

Problem

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); ```

Original source