在Java中显示当前年份的最后两位数字

нαƒ*_*єєz 19 java gregorian-calendar date-formatting

如何在不使用任何子字符串算法或任何第三方库的情况下仅显示当前年份的最后两位数字?

我尝试了下面的方法,它给了一个四位数的年份.我想知道是否有任何日期格式选项可用于以两位数格式获取当前年份.

Calendar.getInstance().get(Calendar.YEAR);
Run Code Online (Sandbox Code Playgroud)

Rob*_*ahl 67

您可以简单地使用模运算符:

int lastTwoDigits = Calendar.getInstance().get(Calendar.YEAR) % 100;
Run Code Online (Sandbox Code Playgroud)

编辑:SimpleDateFormat如果您希望结果为字符串,则使用a ,如@RJ建议的那样,是更好的解决方案.如果需要整数,请使用modulo.

  • 看起来似乎是一个聪明的解决方案,但会导致多年的1位数,如"2001"或0如果它像"2100" (8认同)

Sud*_*hul 36

您可以使用a SimpleDateFormat根据您的要求格式化日期.

DateFormat df = new SimpleDateFormat("yy"); // Just the year, with 2 digits
String formattedDate = df.format(Calendar.getInstance().getTime());
System.out.println(formattedDate);
Run Code Online (Sandbox Code Playgroud)

编辑:根据需要/要求,可以使用我建议的方法或Robin建议的方法.理想情况下,在使用Date处理大量操作时,最好使用DateFormat方法.


Ole*_*.V. 7

这是一个单行:

    System.out.println(Year.now().format(DateTimeFormatter.ofPattern("uu")));
Run Code Online (Sandbox Code Playgroud)

我正在使用java.time.YearJava 8中引入的许多日期和时间类之一(并且还向后移植到Java 6和7).这只是一个小例子了非常多的地方,新的类都比较方便,并导致比老班更清晰的代码CalendarSimpleDateFormat.

如果你只想要两位数字而不是字符串,你可以使用:
Year.now().getValue() % 100.

其他答案在2013年是很好的答案,但岁月已经过去了.:-)