开发者

Increment date by 1 & loop until end of the month

开发者 https://www.devze.com 2023-02-01 19:18 出处:网络
i hav String date & i want to开发者_开发知识库 inceament date by 1 & it should be 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());
}


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.


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);
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消