Java Calendar Add add(Date inputDate, int interval, int calendarUnit)

Here you can find the source of add(Date inputDate, int interval, int calendarUnit)

Description

Add Interval to Date

License

Open Source License

Parameter

Parameter Description
inputDate Date to Add
interval Interval to added. Subtract is interval is nagative
calendarUnit Calendar.Year/Calendar.Month/Calendar.Day/Calendar.Hour/Calendar.MInute

Return

Date added

Declaration

public static Date add(Date inputDate, int interval, int calendarUnit) 

Method Source Code


//package com.java2s;
/*//from   www . j a  va  2  s . co  m
 * File: $RCSfile$
 *
 * Copyright (c) 2005 Wincor Nixdorf International GmbH,
 * Heinz-Nixdorf-Ring 1, 33106 Paderborn, Germany
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Wincor Nixdorf ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered
 * into with Wincor Nixdorf.
 */

import java.util.Date;
import java.util.Calendar;

public class Main {
    /**
     * Add Interval to Date
     *
     * @param inputDate    Date to Add
     * @param interval     Interval to added. Subtract is interval is nagative
     * @param calendarUnit Calendar.Year/Calendar.Month/Calendar.Day/Calendar.Hour/Calendar.MInute
     * @return Date added
     */
    public static Date add(Date inputDate, int interval, int calendarUnit) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(formateDateWithoutTime(inputDate));
        cal.add(calendarUnit, interval);
        return cal.getTime();
    }

    /**
     * Format Date to make it''s hour/minute/second to 0
     *
     * @param inputDate Date to Format
     * @return Date with Year/Month/Day is same with input one while hour/minute/second is 0
     */
    public static Date formateDateWithoutTime(Date inputDate) {
        Date outputDate = inputDate;
        Calendar cal = Calendar.getInstance();
        cal.setTime(outputDate);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        outputDate = cal.getTime();
        return outputDate;
    }
}

Related

  1. add(Calendar calendar, int calendarField, int amount)
  2. add(Date _date, int _calendarField, int _amount)
  3. add(Date date, int calendarField, int amount)
  4. add(final Date date, final int calendarField, final int amount)
  5. add2Calendar(Calendar cal, int years, int months, int days, int hours, int minutes, int seconds, int millis)
  6. addCalendarDate(Calendar cal, int date)
  7. addCalendarMonthsToUnixtime(long time, int interval)