Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.util.Pair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Main {
    /**
     * Get a list of initial and end calendar of months in the range received
     * @param cStart Calendar date to start
     * @param cEnd Calendar date to end
     * @return List<Pair<Calendar, Calendar>> list of calendars (initial and end)
     */
    public static List<Pair<Calendar, Calendar>> getRangeInMonths(Calendar cStart, Calendar cEnd) {

        //generate the list
        List<Pair<Calendar, Calendar>> calendars = new ArrayList<>();

        //from the first calendar start adding a month until the actual calendar is after the end
        Calendar cActual = generateCalendar(cStart);
        cActual.set(Calendar.DAY_OF_MONTH, 1);
        Calendar c0;
        Calendar cF;

        while (cActual.compareTo(cEnd) < 0) {

            //calendar start
            if (calendars.size() == 0) {
                c0 = generateCalendar(cStart);
            } else {
                c0 = generateCalendar(cActual);
            }

            //increment a month
            cActual.add(Calendar.MONTH, 1);

            //calendar end
            if (cActual.after(cEnd)) {
                cF = generateCalendar(cEnd);
            } else {
                cF = generateCalendar(cActual);

                //remove 1 day to set the last day of the month
                cF.add(Calendar.DAY_OF_YEAR, -1);
            }

            //add the pair to the list
            calendars.add(new Pair<Calendar, Calendar>(c0, cF));
        }

        //return the list
        return calendars;
    }

    /**
     * Get Calendar from Date
     * @param date Date
     * @return Calendar generated
     */
    public static Calendar generateCalendar(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(date.getTime());
        return c;
    }

    /**
     * Get Calendar from Date
     * @param cal Calendar
     * @return Calendar generated
     */
    public static Calendar generateCalendar(Calendar cal) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(cal.getTimeInMillis());
        return c;
    }
}