Dilantha Chamal
Dilantha Chamal

Reputation: 49

Increment date by 1 & loop until end of the month

i hav String date & i want to inceament date by 1 & it should be loop until end of the month. as examle, if i take November 2010 it should loop 30 days. if i take December 2010 it should loop 31 days. below shows my code......

String date="12/01/2010";
String incDate;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(date));
for(int co=0; co<30; co++){
    c.add(Calendar.DATE, 1); 
    incDate = sdf.format(c.getTime());
}

Upvotes: 3

Views: 17981

Answers (2)

Tripex
Tripex

Reputation: 1

Another solution could be:

String date = "01/11/2010";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(sdf.parse(date));
        } catch (ParseException ex) {
            Logger.getLogger(DateIterator.class.getName()).log(Level.SEVERE, null, ex);
        }
        int maxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int co = 0; co < maxDay; co++) {
            System.out.println(sdf.format(c.getTime()));
            c.add(Calendar.DATE, 1);
        }

Upvotes: 0

pablochan
pablochan

Reputation: 5715

String date="12/01/2010";
String incDate;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(date));
int maxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
for(int co=0; co<maxDay; co++){
    c.add(Calendar.DATE, 1); 
    incDate = sdf.format(c.getTime());
}

The c.getActualMaximum(Calendar.DAY_OF_MONTH) result will be the last day of the month.

Upvotes: 7

Related Questions