Java Day Add addDays(String s, int day)

Here you can find the source of addDays(String s, int day)

Description

add Days

License

Open Source License

Declaration

public static String addDays(String s, int day) throws Exception 

Method Source Code

//package com.java2s;

public class Main {

    public static String addDays(String s, int day) throws Exception {
        return addDays(s, day, "yyyyMMdd");
    }/*from  w  ww.  j a v a  2  s  .  com*/

    public static String addDays(String s, int day, String format) throws Exception {
        try {

            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format, java.util.Locale.CHINA);
            java.util.Date date = check(s, format);

            date.setTime(date.getTime() + ((long) day * 1000 * 60 * 60 * 24));
            return formatter.format(date);
        } catch (Exception e) {
            throw new Exception("[DateUtil][addDays]" + e.getMessage(), e);
        }
    }

    /**
     * check date string validation with an user defined format.
     *
     * @param s
     *            date string you want to check.
     * @param format
     *            string representation of the date format. For example,
     *            "yyyy-MM-dd".
     * @return date java.util.Date
     */
    private static java.util.Date check(String s, String format) throws java.text.ParseException {
        if (s == null)
            throw new java.text.ParseException("date string to check is null", 0);
        if (format == null)
            throw new java.text.ParseException("format string to check date is null", 0);

        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format, java.util.Locale.CHINA);
        java.util.Date date = null;
        try {
            date = formatter.parse(s);
        } catch (java.text.ParseException e) {
            /*
             * throw new java.text.ParseException( e.getMessage() + " with
             * format \"" + format + "\"", e.getErrorOffset() );
             */
            throw new java.text.ParseException(" wrong date:\"" + s + "\" with format \"" + format + "\"", 0);
        }

        if (!formatter.format(date).equals(s))
            throw new java.text.ParseException("Out of bound date:\"" + s + "\" with format \"" + format + "\"", 0);
        return date;
    }
}

Related

  1. addDays(Integer dateAsInt, Integer daysToAdd)
  2. addDays(java.util.Date value, final int days)
  3. AddDays(long initialDateMilliSeconds, int dayNumber)
  4. addDays(String dateStr, int days)
  5. addDays(String dateStr, int nDays, String inputDateFormat, String outputDateFormat)
  6. addDays(String src, int day, String format)
  7. addDays(String startDate, int amount)
  8. addDays2Date(Date d, int days)
  9. addDays2Date(String str, int days)