Java Date Between daysBetween(String from, String to, String format)

Here you can find the source of daysBetween(String from, String to, String format)

Description

days Between

License

Open Source License

Declaration

public static int daysBetween(String from, String to, String format) throws Exception 

Method Source Code

//package com.java2s;

public class Main {

    public static int daysBetween(String from, String to) throws Exception {
        return daysBetween(from, to, "yyyyMMdd");
    }//from   w w  w.  ja  va2s  .  c  om

    public static int daysBetween(String from, String to, String format) throws Exception {
        // java.text.SimpleDateFormat formatter =
        // new java.text.SimpleDateFormat (format, java.util.Locale.CHINA);
        try {

            java.util.Date d1 = check(from, format);
            java.util.Date d2 = check(to, format);

            long duration = d2.getTime() - d1.getTime();

            return (int) (duration / (1000 * 60 * 60 * 24));
            // seconds in 1 day
        } catch (Exception e) {
            throw new Exception("[DateUtil][daysBetween]" + 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. daysBetween(final Date dateA, final Date dateB)
  2. daysBetween(String bdate, String edate)
  3. daysBetween(String beginDate, String endDate)
  4. daysBetween(String from, String to)
  5. daysBetween(String from, String to, String form)
  6. daysBetween(String from, String to, String format)
  7. daysBetween(String smdate, String bdate)
  8. daysBetween2Dates(Date d1, Date d2)
  9. daysBetween2Dates(Date startDate, Date endDate)