get Number Of Days In Apart Exclusive - Android java.util

Android examples for java.util:Day

Description

get Number Of Days In Apart Exclusive

Demo Code


//package com.java2s;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static int getNumberOfDaysInApartExclusive(Date startDate,
            Date endDate) {/*from   w  ww  .  j a  v a2  s  .  com*/
        if (startDate == null || endDate == null) {
            return 0;
        }

        Calendar endCal = Calendar.getInstance();
        endCal.setTime(endDate);

        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startDate);

        int endYear = endCal.get(Calendar.YEAR);
        int startYear = startCal.get(Calendar.YEAR);

        int endDayOfYear = endCal.get(Calendar.DAY_OF_YEAR);
        int startDayOfYear = startCal.get(Calendar.DAY_OF_YEAR);

        if (endYear == startYear) {
            return endDayOfYear - startDayOfYear;
        } else {
            int daysInFuture = 0;

            // days left in this year
            daysInFuture += startCal.getActualMaximum(Calendar.DAY_OF_YEAR)
                    - startDayOfYear;

            // days from start of end year
            daysInFuture += endDayOfYear;

            // all the days in the in-between years
            for (int year = startYear + 1; year < endYear; year++) {
                Calendar yearCal = Calendar.getInstance();
                yearCal.set(year, Calendar.JANUARY, 1);
                daysInFuture += yearCal
                        .getActualMaximum(Calendar.DAY_OF_YEAR);
            }

            return daysInFuture;
        }
    }
}

Related Tutorials