Roll the years forward or backward in Java
Description
The following code shows how to roll the years forward or backward.
Example
/* w ww . j av a2 s. c o m*/
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main {
/**
* Roll the years forward or backward.
*
* @param startDate
* - The start date
* @param years
* - Negative to rollbackwards.
*/
public static java.sql.Date rollYears(java.util.Date startDate, int years) {
return rollDate(startDate, Calendar.YEAR, years);
}
/**
* Roll the java.sql.Date forward or backward.
*
* @param startDate
* - The start date
* @period Calendar.YEAR etc
* @param amount
* - Negative to rollbackwards.
*/
public static java.sql.Date rollDate(java.util.Date startDate, int period,
int amount) {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(startDate);
gc.add(period, amount);
return new java.sql.Date(gc.getTime().getTime());
}
public static void main(String[] argv) {
System.out.println(rollYears(new Date(), 10));
}
}
The code above generates the following result.