Return existing dates between two other dates - Android

1

I would like to know if there is any class or library that returns the existing dates between two dates I pass.

For example: I would pass the dates 23/02/2016 and 25/02/2016 and would return the date 02/24/2016.

I saw many methods teaching how to return the amount of dates between two dates, that would not be what I need, and I imagine that creating a class to do what I'm asking would give me a lot of work, so I decided to take the risk to see if anyone knows if any method already exists to do this.

    
asked by anonymous 23.02.2016 / 21:01

1 answer

2

Try the following:

EDITED

According to the comment in the comment, there is a need to decrease 1 in the month to set a Date (% with%) to String .

Example:

final String[] valI = inicio.split("/");
cINI.set(Calendar.DAY_OF_MONTH, Integer.valueOf(valI[0])-1);

Thinking about this and in order to simplify the code a little, follow the modified method:

public static List<String> diferencaDeDatas(String inicio, String fim) throws ParseException{
    // Tranforma Date em String e vice-versa
    final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    Calendar c = Calendar.getInstance(); 
    // Clonamos os Calendar para não ter a mesma referencia
    Calendar cINI = (Calendar) c.clone();
    Calendar cFIM = (Calendar) c.clone();

    //Transformamos a STring em java.util.Date
    Date dtIni = sdf.parse(inicio);
    Date dtFim = sdf.parse(fim);

    // Setamos dos java.util.Date nos Calendar's 
    cINI.setTimeInMillis(dtIni.getTime());
    cFIM.setTimeInMillis(dtFim.getTime());

    // Se a data final for menor que a maior ou igual  retorna uma lista vazia...
    if(cFIM.getTimeInMillis() <= cINI.getTimeInMillis()){
        return new ArrayList<>(0);
    }
    // Lista que vamos retonar com o valores
    List<String> itens = new ArrayList<>(0);

    // adicionamos +1 dia, pois não iremos contar o dia inicial
    cINI.set(Calendar.DAY_OF_MONTH, cINI.get(Calendar.DAY_OF_MONTH)+1);

    // vamos realizar a acão enquanto a data inicial for menor q a final
    while(cINI.getTimeInMillis() < cFIM.getTimeInMillis()){
        // adicionamos na lista...
        itens.add(sdf.format(cINI.getTime()));
        // adicionamos +1 dia....
        cINI.set(Calendar.DAY_OF_MONTH, cINI.get(Calendar.DAY_OF_MONTH)+1);
    }

    return itens;
}
    
23.02.2016 / 21:33