Java Year From yearsBetween(String from, String to)

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

Description

years Between

License

Open Source License

Declaration

public static int yearsBetween(String from, String to) throws Exception 

Method Source Code

//package com.java2s;

public class Main {

    public static int yearsBetween(String from, String to) throws Exception {
        return yearsBetween(from, to, "yyyyMMdd");
    }// w ww.  j a v a2 s .  co  m

    public static int yearsBetween(String from, String to, String format) throws Exception {
        return (int) (daysBetween(from, to, format) / 365);
    }

    public static int daysBetween(String from, String to) throws Exception {
        return daysBetween(from, to, "yyyyMMdd");
    }

    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. yearformMatDate(Date date)
  2. yearFromDate(String date)
  3. yearFromDateValue(long x)
  4. yearFromFileName(String str)
  5. yearOfDate(Date s)