Date increment by 1 & loop to end of month

i hav String date, and I want the insert date to be 1, and it should be loopback by the end of the month. as an example, if I take November 2010, it should take 30 days. if I take December 2010, it should take 31 days. my code is shown below ......

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());
}
+3
source share
2 answers
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 result c.getActualMaximum(Calendar.DAY_OF_MONTH)will be the last day of the month.

+6
source

Another solution might 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
source

Source: https://habr.com/ru/post/1782155/


All Articles