-1

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?

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
BigRedEO
  • 807
  • 4
  • 13
  • 33
  • 2
    Would it work? Can you try it? – NotZack Apr 29 '19 at 17:35
  • @NotZack At the moment - don't have a chance to test - I'm waiting on someone else to finish up before I can get into the project. Wanted to research this now. – BigRedEO Apr 29 '19 at 17:37
  • 4
    @BigRedEO You should have started a new project to test this out. No need to wait on your current project, whatever that is. You may also want to look at source control (e.g 'git') so you're not waiting on other people to edit a project. – dustytrash Apr 29 '19 at 18:08

2 Answers2

10

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().

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
  • 1
    New Year doesn’t happen simultaneously in all time zones, so for a predictable result around that time I suggest you give time zone explicitly, for example `Year.now(ZoneId.of("Europe/Berlin"))`. – Ole V.V. May 02 '19 at 14:14
7

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
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63