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