This method returns new date by adding (subtracting) days to the original date. - Java java.util

Java examples for java.util:Day

Description

This method returns new date by adding (subtracting) days to the original date.

Demo Code


//package com.java2s;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] argv) throws Exception {
        Date date = new Date();
        int daysToAdd = 2;
        System.out.println(getDateByAddDays(date, daysToAdd));
    }/*from  w  w  w .j a  v a  2 s.c  o m*/

    /**
     * This method returns new date by adding (subtracting) days to the original date.
     *
     * @param date
     *          base date
     * @param daysToAdd
     *          amount of days to add or subtract (negative values)
     * @return the returned date is normalized
     */
    public static Date getDateByAddDays(Date date, int daysToAdd) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 1);
        calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);
        return calendar.getTime();
    }
}

Related Tutorials