Adds the specified (signed) amount of days to the given time field, based on the calendar's rules. - Java java.util

Java examples for java.util:Calendar Calculation

Description

Adds the specified (signed) amount of days to the given time field, based on the calendar's rules.

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 value = 2;
        System.out.println(addDay(date, value));
    }// w w  w. jav  a2  s  .  c  o  m

    /**
     * Date Arithmetic function. Adds the specified (signed) amount of days to
     * the given time field, based on the calendar's rules. For example, to
     * subtract 5 days to a date of the calendar, you can achieve it by calling:
     * <p/>
     * addDay(new Date() , -5)
     * <p/>
     * To add 5 days to date, you can achieve it by calling: addDay(new Date()
     * ,5) <br/>
     * 
     * @param date
     *            Date
     * @param value
     *            Value which is to be added or subtracted
     * @return Date
     */
    public static Date addDay(Date date, int value) {
        return add(date, Calendar.DATE, value);
    }

    /**
     * Date Arithmetic function. Adds the specified (signed) amount of time to
     * the given time field, based on the calendar's rules. For example, to
     * subtract 5 days to a date of the calendar, you can achieve it by calling:
     * <p/>
     * add(new Date() ,Calendar.DATE, -5)
     * <p/>
     * To add 5 days to date, you can achieve it by calling: add(new Date()
     * ,Calendar.DATE, s5) <br/>
     * For details on values for <code>field</code>, refer {@link Calendar}
     * 
     * @param date
     *            Date
     * @param field
     *            Field to which the addition and subtraction
     * @param value
     *            Value which is to be added or subtracted
     * @return Date
     */
    public static Date add(Date date, int field, int value) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(field, value);
        return cal.getTime();
    }
}

Related Tutorials