int year = Calendar.getInstance().get(Calendar.YEAR);
不确定这是否符合不设定新日历的标准? (为什么反对派这样做?)
使用Java 8的时间API(假设您很高兴在系统的默认时区获得Year::now ),您可以使用Year::now方法 :
int year = Year.now().getValue();
这个最简单的(使用日历,抱歉)是:
int year = Calendar.getInstance().get(Calendar.YEAR);
还有新的date和时间API JSR以及Joda Time
最简单的方法是从日历中获取年份。
// year is stored as a static member int year = Calendar.getInstance().get(Calendar.YEAR);
如果你想要任何date对象的年份,我使用以下方法:
public static int getYearFromDate(Date date) { int result = -1; if (date != null) { Calendar cal = Calendar.getInstance(); cal.setTime(date); result = cal.get(Calendar.YEAR); } return result; }
如果您的应用程序正在大量使用Date和Calendar对象,则应该使用Joda Time,因为java.util.Date是可变的。 java.util.Calendar在更新字段时会出现性能问题,并且对于date时间algorithm来说是笨重的。
有些人回答如上&#x