BigRedEO
BigRedEO

Reputation: 847

Get current year for variable - Java

I have three variables where I need the current year, one year ago from the present time, and two years ago from the present time, using Java. Would something like this work?:

String DNRCurrentYear = new SimpleDateFormat("yyyy").format(new Date());

Or do I need to make the year an int in order to subtract one, then two years from?

How would I get the current year minus one, and current year minus two?

Upvotes: -1

Views: 8577

Answers (2)

Michał Krzywański
Michał Krzywański

Reputation: 16930

Use LocalDate class from 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());
}

Output:

YEAR : 2019
YEAR : 2018
YEAR : 2017

Upvotes: 7

Samuel Philipp
Samuel Philipp

Reputation: 11050

You can use the Java 8 Year class and its Year.minusYears() method:

Year year = Year.now();
Year lastYear = year.minusYears(1);
// ...

To get the int value you can use year.getValue(). To get the String value you can use year.toString().

Upvotes: 10

Related Questions