Displaying the last two digits of the current year in Java

◇◆丶佛笑我妖孽 提交于 2019-11-29 03:06:51

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. :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!