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

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

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

Calendar.getInstance().get(Calendar.YEAR); 

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

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

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

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

 int lastTwoDigits = Calendar.getInstance().get(Calendar.YEAR) % 100; 

编辑:如果你希望结果是一个字符串,使用SimpleRateFormat,就像@RJ提出的那样,是更好的解决方案。 如果需要整数,请使用modulo。

这是一个单行:

  System.out.println(Year.now().format(DateTimeFormatter.ofPattern("uu"))); 

我正在使用java.time.Year ,它是Java 8中引入的许多日期和时间类之一(并且还向后移植到Java 6和7)。 这只是很多例子中的一个例子,新类更方便,并且导致代码比旧类CalendarSimpleDateFormat更清晰。

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

其他答案在2013年是很好的答案,但这些年来一直在继续。 🙂