Java Date Add dateAdd(final Date baseDateTime, int daysToAdd, boolean chopTime)

Here you can find the source of dateAdd(final Date baseDateTime, int daysToAdd, boolean chopTime)

Description

Method dateAdd.

License

Open Source License

Parameter

Parameter Description
baseDateTime a parameter
daysToAdd a parameter
chopTime a parameter

Return

Date

Declaration

public static Date dateAdd(final Date baseDateTime, int daysToAdd, boolean chopTime) 

Method Source Code

//package com.java2s;

import java.text.ParseException;
import java.text.SimpleDateFormat;

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

public class Main {
    /**//w w w  . ja  v  a  2 s  .com
     * Method dateAdd.
     * 
     * @param baseDateTime
     * @param daysToAdd
     * @param chopTime
     * @return Date
     */
    public static Date dateAdd(final Date baseDateTime, int daysToAdd, boolean chopTime) {
        if (baseDateTime == null)
            throw new RuntimeException("Null date passed to Utils.dateAdd.");

        Date dateTime = baseDateTime;
        if (chopTime)
            dateTime = getMidnight(dateTime);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        calendar.add(Calendar.DATE, daysToAdd);
        return calendar.getTime();
    }

    /**
     * Method dateAdd. Return midight-based date by adding the number of days to the given date. Account for changes
     * to/from daylight savings time.
     * 
     * @param baseDateTime
     * @param daysToAdd
     * @return Date
     */
    public static Date dateAdd(Date baseDateTime, int daysToAdd) {
        return dateAdd(baseDateTime, daysToAdd, true);
    }

    /**
     * Gets the midnight.
     * 
     * @param date the date
     * 
     * @return the midnight
     */
    public static Date getMidnight(Date date) {
        if (date == null)
            throw new IllegalArgumentException("'date' parameter must be valued.");

        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            return formatter.parse(formatter.format(date));
        } catch (ParseException e) {
            throw new RuntimeException("Unexpected ParseException for date '" + date + "'.", e);
        }
    }

    /**
     * Gets the midnight java.util.Date for the midnight at the beginning of the current date
     * 
     * @return the midnight
     */
    public static Date getMidnight() {
        return getMidnight(new Date());
    }
}

Related

  1. dateAdd(Date date, int days)
  2. dateAdd(Date date, int days)
  3. dateAdd(Date date, int field, int amount)
  4. dateAdd(Date date, int type, int num)
  5. dateAdd(Date date, int val)
  6. dateAdd(int datePart, int amount, Date date)
  7. dateAdd(int interval, Date date, int n)
  8. DateAdd(String strDate, int iCount, int iType)
  9. DateAdd3Days(String _date)