我需要在Java中确定当前年份为整数。我可以只使用java.util.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;
}

其他回答

正如上面有人回答的那样:

如果你以后想使用这个变量,最好使用:

int year;

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

如果你只需要一个年份,你最好使用:

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

例如,在do中使用它,而检查引入的年份不小于当前年份200或大于当前年份(可能是出生年份):

import java.util.Calendar;
import java.util.Scanner;

public static void main (String[] args){

    Scanner scannernumber = new Scanner(System.in);
    int year;

    /*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/

    do{
        System.out.print("Year (Between "+((Calendar.getInstance().get(Calendar.YEAR))-200)+" and "+Calendar.getInstance().get(Calendar.YEAR)+") : ");
        year = scannernumber.nextInt();
    }while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));
}

使用Java 8的时间API(假设你很高兴得到系统默认时区中的年份),你可以使用year::now方法:

int year = Year.now().getValue();

在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看起来更好,并且可以使其具有区域感知。

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

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

这个最简单的(使用日历,抱歉)是:

 int year = Calendar.getInstance().get(Calendar.YEAR);

还有新的日期和时间API JSR,以及Joda Time