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

Java examples for java.util:Second

Description

Adds the specified (signed) amount of seconds 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(addSeconds(date, value));
    }// w ww  .j ava 2s  . co m

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