Java Date Between betweenDate(String from, String to)

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

Description

between date

License

Open Source License

Parameter

Parameter Description
from (yyyyMMdd or yyyyMMddHHmmss)
to (yyyyMMdd or yyyyMMddHHmmss)

Return

between date

Declaration

public static long betweenDate(String from, String to) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;

public class Main {
    private final static int MILLIS_PER_HOUR = 3600000;

    /**/*from  w  w w  .jav a2 s.c  om*/
    * between date
    * @param from (yyyyMMdd or yyyyMMddHHmmss)
    * @param to (yyyyMMdd or yyyyMMddHHmmss)
    * @return between date
    */
    public static long betweenDate(String from, String to) {
        if (from == null) {
            throw new IllegalArgumentException("from can not be null");
        }
        if (to == null) {
            throw new IllegalArgumentException("to can not be null");
        }

        int len = from.length();
        if (!(len == 8 || len == 14)) {
            throw new IllegalArgumentException("from length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");
        }

        if (len == 8) {
            from += "090000";
        }

        len = to.length();
        if (!(len == 8 || len == 14)) {
            throw new IllegalArgumentException("to length must be 8 or 14 (yyyyMMdd or yyyyMMddHHmmss)");
        }

        if (len == 8) {
            to += "090000";
        }

        return betweenDate(getDate(from), getDate(to));
    }

    /**
    * between date
    * @param from java.util.Date from
    * @param to java.util.Date to
    * @return long
    */
    public static long betweenDate(java.util.Date from, java.util.Date to) {
        return new Double(Math.ceil((to.getTime() - from.getTime()) / (MILLIS_PER_HOUR * 24f))).longValue();
    }

    /**
    * yyyyMMddHHmmss --> java.util.Date
    * @param String dt
    * @return java.util.Date
    */
    private static java.util.Date getDate(String dt) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.valueOf(dt.substring(0, 4)).intValue(), Integer.valueOf(dt.substring(4, 6)).intValue() - 1,
                Integer.valueOf(dt.substring(6, 8)).intValue(), Integer.valueOf(dt.substring(8, 10)).intValue(),
                Integer.valueOf(dt.substring(10, 12)).intValue(), Integer.valueOf(dt.substring(12, 14)).intValue());

        return cal.getTime();
    }
}

Related

  1. between(Date beginDate, Date endDate)
  2. between(Date d, Date startDate, Date endDate)
  3. between(Date kezdet, Date veg, Date datum)
  4. between(Date since, Date until, Date dateIn, Date dateOut)
  5. between(Date smdate, Date bdate)
  6. betweenHour(Date date, int hour)
  7. betweenInDay(Date date, Date start, Date end)
  8. betweenStartDateAndEndDate(Date startDate, Date endDate)
  9. betweenStrict(Date kezdet, Date datum, Date veg)