Reputation: 847
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
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
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