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

Java examples for java.util:Hour

Description

Adds the specified (signed) amount of hours 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(addHour(date, value));
    }//from  ww w. j  a  va  2 s  . c  o m

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