How to Add Or Subtract Years in Java


Here we will write an example to add or substract years in current date and time values with java Calendar class.

Source Code

package com.beginner.examples;

import java.util.Calendar;

public class ASYearsExample {

    public static void main(String[] args){
    	//get calendar
    	Calendar now = Calendar.getInstance();
    	System.out.println(now.get(Calendar.YEAR));
		//years add 1
    	now.add(Calendar.YEAR, 1);
		System.out.println(now.get(Calendar.YEAR));
		//years subtract 1
		now.add(Calendar.YEAR, -1);
		System.out.println(now.get(Calendar.YEAR));
	}
}

Output:

2019
2020
2019

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments