Java Date Between getBetweenDateBuckets(Date from, Date to)

Here you can find the source of getBetweenDateBuckets(Date from, Date to)

Description

From/to inclusive

License

Open Source License

Parameter

Parameter Description
from a parameter
to a parameter

Declaration

public static List<Date> getBetweenDateBuckets(Date from, Date to) 

Method Source Code

//package com.java2s;

import java.util.ArrayList;
import java.util.Calendar;

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

import java.util.List;

public class Main {
    /**/*ww  w. j a  v  a  2  s .  c  o  m*/
     * From/to inclusive
     * @param from
     * @param to
     * @return
     */
    public static List<Date> getBetweenDateBuckets(Date from, Date to) {
        final List<Date> buckets = new ArrayList<>();

        if (to.after(from)) {

            Calendar f = dateToCalendar(from);
            Calendar t = dateToCalendar(to);

            int gap = gapInDays(f, t);
            buckets.add(from);
            for (int i = 1; i <= gap; i++) {
                buckets.add(addDays(from, i));
            }
        }
        return buckets;

    }

    public static Calendar dateToCalendar(Date d) {
        Calendar c1 = new GregorianCalendar();
        c1.setTime(d);
        return c1;
    }

    static int gapInDays(Calendar a, Calendar b) {
        //same year
        if (a.get(Calendar.YEAR) == b.get(Calendar.YEAR)) {
            return b.get(Calendar.DAY_OF_YEAR) - a.get(Calendar.DAY_OF_YEAR);
        }
        //consecutive year
        else if (a.get(Calendar.YEAR) + 1 == b.get(Calendar.YEAR)) {
            return a.getMaximum(Calendar.DAY_OF_YEAR) + b.get(Calendar.DAY_OF_YEAR) - a.get(Calendar.DAY_OF_YEAR);

        } else
            return 0;
    }

    public static Date addDays(Date d, int n) {
        Calendar c = dateToCalendar(d);
        c.add(Calendar.DAY_OF_MONTH, n);
        return c.getTime();
    }
}

Related

  1. daysBetweenDate(Integer startDate, Integer endDate)
  2. daysBetweenDates(Date beginDate, Date endDate)
  3. daysBetweenMidnight(final Date startDate, final Date endDate)
  4. getBetweenDate(Date startDate, Date endDate)
  5. getBetweenDate(String d1, String d2)
  6. getBetweenDates(Date fromDate, Date toDate )
  7. getBetweenDays(String strFromDate, String strToDate)
  8. getBetweenMonths(Date date1, Date date2)
  9. getBetweenTime(Date begin, Date end, int field)