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

Java examples for java.util:Year

Description

Adds the specified (signed) amount of year 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(addYear(date, value));
    }/*from w  w w .ja  v a2 s  .  c o  m*/

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