我需要在Java中确定当前年份为整数。我可以只使用java.util.Date(),但已弃用。


当前回答

最简单的方法是从Calendar中获取年份。

// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);

其他回答

你也可以使用java.time中的2个方法。年月(自Java 8起):

import java.time.YearMonth;
...
int year = YearMonth.now().getYear();
int month = YearMonth.now().getMonthValue();

在Java版本8+可以(建议)使用Java。图书馆的时间。ISO 8601设置了写入日期的标准方式:YYYY-MM-DD和java.time.Instant使用它,因此(对于UTC):

import java.time.Instant;
int myYear = Integer.parseInt(Instant.now().toString().substring(0,4));

附注:以防万一(是获取字符串的缩写,不是int),使用Calendar看起来更好,并且可以使其具有区域感知。

最简单的方法是从Calendar中获取年份。

// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);

你可以使用Integer数学来完成整个事情,而不需要实例化一个日历:

return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);

新年的时候可能会休息一两个小时,但我不觉得这是个问题?

如果您的应用程序大量使用Date和Calendar对象,那么您确实应该使用Joda Time,因为java.util.Date是可变的。calendar在字段更新时存在性能问题,并且对于日期时间算法来说很笨拙。