Java Month Calculate divideIntoMonthlyIntervals(Date start, Date end)

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

Description

returns a list of monthly intervals for the first of each month the first entry in the list is the 1st of the month before start and the last entry is the 1st of the month after the end.

License

Apache License

Declaration

public static List<Date> divideIntoMonthlyIntervals(Date start, Date end) 

Method Source Code

//package com.java2s;
/*/*from   w w  w.j  ava 2  s.co  m*/
 Copyright (C) 2012 The Stanford MobiSocial Laboratory
    
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
    
   http://www.apache.org/licenses/LICENSE-2.0
    
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

import java.util.*;

public class Main {
    /** returns a list of monthly intervals for the first of each month
     * the first entry in the list is the 1st of the month before start
     * and the last entry is the 1st of the month after the end.
     */
    public static List<Date> divideIntoMonthlyIntervals(Date start, Date end) {
        List<Date> result = new ArrayList<Date>();

        // result will always have at least 2 entries
        Calendar c = startOfMonth(start);
        result.add(c.getTime());
        do {
            int mm = c.get(Calendar.MONTH);
            int yy = c.get(Calendar.YEAR);
            mm++;
            // months are 0-based (jan = 0)
            if (mm >= 12) {
                mm = 0;
                yy++;
            }
            c = new GregorianCalendar(yy, mm, 1);
            result.add(c.getTime());
        } while (c.getTime().before(end)); // stop when we are beyond end

        return result;
    }

    public static Calendar startOfMonth(Date d) {
        Calendar c = new GregorianCalendar();
        c.setTime(d);
        int yy = c.get(Calendar.YEAR);
        int mm = c.get(Calendar.MONTH);
        // get new date with day of month set to 1
        c = new GregorianCalendar(yy, mm, 1);
        return c;
    }
}

Related

  1. alignMonth(Calendar timestamp)
  2. beforeAMonth()
  3. calendarMonthToInt(int calendarMonth)
  4. currentMonth()
  5. endOfLastMonth()
  6. getAgeInMonths(Date startDate, Date endDate)
  7. getAlphaMonth(String mon)
  8. getCurrentMonth()