获取变量-Java的当前年份

获取变量-Java的当前年份,java,date,java-calendar,Java,Date,Java Calendar,我有三个变量,其中我需要当前年份,一年前从现在开始,两年前从现在开始,使用Java。你喜欢这个工作吗 String DNRCurrentYear = new SimpleDateFormat("yyyy").format(new Date()); 或者我需要将年份设为int,以便从中减去一年,然后再减去两年 如何获得当前年份减去1和当前年份减去2?您可以使用Java 8类及其方法: 要获取int值,可以使用year.getValue()。要获取字符串值,可以使用year.toString()使

我有三个变量,其中我需要当前年份,一年前从现在开始,两年前从现在开始,使用Java。你喜欢这个工作吗

String DNRCurrentYear = new SimpleDateFormat("yyyy").format(new Date());
或者我需要将年份设为
int
,以便从中减去一年,然后再减去两年

如何获得当前年份减去1和当前年份减去2?

您可以使用Java 8类及其方法:

要获取int值,可以使用
year.getValue()
。要获取字符串值,可以使用
year.toString()

使用Java 8中的类:

public static void main(String[] args) {
    LocalDate now = LocalDate.now();
    System.out.println("YEAR : " + now.getYear());

    LocalDate oneYearBeforeDate = now.minus(1, ChronoUnit.YEARS);
    System.out.println("YEAR : " + oneYearBeforeDate.getYear());

    LocalDate twoYearsBeforeDate = now.minus(2, ChronoUnit.YEARS);
    System.out.println("YEAR : " + twoYearsBeforeDate.getYear());
}
输出:

YEAR : 2019
YEAR : 2018
YEAR : 2017

这样行吗?你能试试吗?@NotZack目前-没有机会测试-在我进入项目之前,我正在等待其他人完成。现在想研究一下。@BigRedEO你应该开始一个新项目来测试一下。无需等待您当前的项目,无论是什么。您可能还想查看源代码管理(例如“git”),这样您就不用等待其他人来编辑项目。新年并非在所有时区都同时发生,因此,为了获得可预测的结果,我建议您明确给出时区,例如
Year.now(ZoneId.of(“Europe/Berlin”)
YEAR : 2019
YEAR : 2018
YEAR : 2017