java 将日期增加 1 并循环至月底

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4533446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:48:00  来源:igfitidea点击:

Increment date by 1 & loop until end of the month

javadate

提问by Dilantha Chamal

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......

我有字符串日期 & 我想将日期增加 1 & 它应该循环到月底。例如,如果我选择 2010 年 11 月,它应该循环 30 天。如果我选择 2010 年 12 月,它应该循环 31 天。下面显示了我的代码......

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

回答by pablochan

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.

c.getActualMaximum(Calendar.DAY_OF_MONTH)结果将是这个月的最后一天。

回答by Tripex

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