Displaying the last two digits of the current year in Java

醉酒当歌 提交于 2019-11-27 17:25:17

问题


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

回答1:


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.




回答2:


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.




回答3:


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

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