I need to get a list of dates whose days are "Monday" in a supplied date range, inclusive.
For example:
If we pass the interval 05/01/2017 to 05/15/2017, the function should return:
05/01/2017
05/08/2017
05/15/2017
My code is the following:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
List<String> dates = new ArrayList<String>();
Calendar cini = Calendar.getInstance();
cini.setTime(formatter.parse(peticion.getDiaInicio()));
Calendar cfin = Calendar.getInstance();
cfin.setTime(formatter.parse(peticion.getDiaFin()));
while (cfin.after(cini)) {
if (cini.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
logger.info("---------->" + cini.getTime().toString() + " es Lunes ");
dates.add(formatter.format(cini.getTime()));
}
cini.add(Calendar.DATE, 1);
}
for(String c : dates){
System.out.println("Fecha: " + c);
}
With this code it is only returning the first two values:
05/01/2017
05/08/2017
Any suggestion?
The problem is the condition of the
while
. When it reaches the third iteration,cini=15/05/2017
,cini
andcfin
are equal, socfin.after(cini)
.A possible solution would be to change the condition to
In your while condition you must add one more question, if cfin is equal to cini:
This way you make sure that it compares the last given date
Seeing as no one has picked up the gauntlet...
A little more generalized here: https://ideone.com/v2yTVj