Java Day Between getDaysBetween(Date start, Date end)

Here you can find the source of getDaysBetween(Date start, Date end)

Description

get Days Between

License

Open Source License

Declaration

public static int getDaysBetween(Date start, Date end) 

Method Source Code

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

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

public class Main {

    public static int getDaysBetween(Date start, Date end) {
        if (start == null)
            return 0;
        boolean negative = false;
        if (end.before(start)) {
            negative = true;/*from  w  ww  .  j a v a  2  s .c  o  m*/
            Date temp = start;
            start = end;
            end = temp;
        }
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(start);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        GregorianCalendar calEnd = new GregorianCalendar();
        calEnd.setTime(end);
        calEnd.set(Calendar.HOUR_OF_DAY, 0);
        calEnd.set(Calendar.MINUTE, 0);
        calEnd.set(Calendar.SECOND, 0);
        calEnd.set(Calendar.MILLISECOND, 0);
        if (cal.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)) {
            if (negative)
                return (calEnd.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)) * -1;
            return calEnd.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
        }
        int counter = 0;
        while (calEnd.after(cal)) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            counter++;
        }
        if (negative)
            return counter * -1;
        return counter;
    }

    public static int get(Date date, int type) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(type);
    }
}

Related

  1. getDateDifference(Date date1, Date date2)
  2. getDateDifferenceinDays(Date date1, Date date2)
  3. getDateDiffYear(Date date, int diff, String... format)
  4. getDateWithDiff(Date date, int amount)
  5. getDaysBetween(Date date1, Date date2)
  6. getDaysBetween(Date start, Date end)
  7. getDaysBetween(Date startDate, Date endDate)
  8. getDaysBetween(Date startDate, Date endDate)
  9. getDaysBetweenDate(Date begin, Date end)