Adds the specified (signed) amount of time 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 time 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 field = 2;
        int value = 2;
        System.out.println(add(date, field, value));
    }/*from   w w w  .  ja v  a 2  s.com*/

    /**
     * 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