iterator Month - Java java.util

Java examples for java.util:Month

Description

iterator Month

Demo Code


//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    public static Iterator<Date> iteratorMonth(String begin, int end) {
        List<Date> ls = new ArrayList<Date>();
        try {//from   w  ww .ja  v a 2s.c o  m
            Date beginDate = sdf.parse(begin);
            //         System.out.println(beginDate);
            Calendar cl = Calendar.getInstance();
            cl.setTime(beginDate);
            ls.add(beginDate);
            for (int i = 0; i < end; i++) {
                cl.add(Calendar.MONTH, 1);
                ls.add(cl.getTime());
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

        return ls.iterator();
    }

    public static Iterator<Date> iteratorMonth(String begin, String end) {
        List<Date> ls = new ArrayList<Date>();
        int endtime = monthRange(begin, end);
        try {
            Date beginDate = sdf.parse(begin);
            //         System.out.println(beginDate);
            Calendar cl = Calendar.getInstance();
            cl.setTime(beginDate);
            ls.add(beginDate);
            for (int i = 0; i < endtime; i++) {
                cl.add(Calendar.MONTH, 1);
                ls.add(cl.getTime());
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

        return ls.iterator();
    }

    public static Integer monthRange(String begin, String end) {
        Date start = null;
        Date stop = null;
        try {
            start = sdf.parse(begin);
            stop = sdf.parse(end);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        int rangeyear = stop.getYear() - start.getYear();
        int rangemonth = stop.getMonth() - start.getMonth();

        Integer result = null;
        if (rangeyear > 0) {
            result = rangeyear * 12 + rangemonth;
        } else {
            result = rangemonth;
        }
        return result;
    }
}

Related Tutorials