Android Date Add addHoursToDate(Date date, int hoursToBeAdded)

Here you can find the source of addHoursToDate(Date date, int hoursToBeAdded)

Description

Add / Subtract given no of hours to Date .

Parameter

Parameter Description
date - Date object.
hoursToBeAdded -amount by which to be changed.

Exception

Parameter Description
NullPointerException if any of the parameters is null.

Return

-new object with updated time.

Declaration

public static Date addHoursToDate(Date date, int hoursToBeAdded) 

Method Source Code

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Main{
    /***//  w  w w. j a v  a  2s . c  o m
     *  Add / Subtract given no of hours to {@link Date}.
     *  
     * @param date -{@link Date} object.
     * @param hoursToBeAdded -amount by which to be changed.
     * @return -new {@link Date} object with updated time.
     * @throws NullPointerException if any of the parameters is null. 
     */
    public static Date addHoursToDate(Date date, int hoursToBeAdded) {
        if (StringUtils.isNull(date)) {
            throw new NullPointerException("date cannot be null");
        }
        return add(date, Calendar.HOUR, hoursToBeAdded);
    }
    /**
     * Used internally to add/subtract amount to specific calendar field.
     * 
     * @param date -{@link Date} object.
     * @param calendarField -calendar specific field.
     * @param amount -int, value by which field should be changed.
     * @return -new {@link Date} object with updated time.
     * @throws NullPointerException if any of the parameters is null.
     */
    private static Date add(Date date, int calendarField, int amount) {
        if (StringUtils.isNull(date)) {
            throw new NullPointerException("date cannot be null");
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }
}

Related

  1. addDays(Date date, int amount)
  2. addDays(Date date, int amount)
  3. addDaysToDate(Date date, int daysToBeAdded)
  4. addHours(Date date, int amount)
  5. addHours(Date date, int amount)
  6. addMilliseconds(Date date, int amount)
  7. addMilliseconds(Date date, int amount)
  8. addMinuteToDate(Date date, int minutesToBeAdded)
  9. addMinutes(Date date, int amount)