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);
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.
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.
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. :-)
来源:https://stackoverflow.com/questions/20070258/displaying-the-last-two-digits-of-the-current-year-in-java