JAVA Date Comparison

1

Good people I have a array of strings with dates, coming from a query with Firebase database. I want to organize it in a growing number of dates.

Ex: 05/09/2016 - 09/09/2016 - 11/11/2016

Dates are entered into my array by the populateViewHolder method:

protected void populateViewHolder(RoomViewHolder viewHolder, EscapeRoom model, int position)
        {
            String [] datasBancoDeDados = new String[] {model.getData()} ;
        }

At each method execution it adds a date to my array.

My goal is to organize this array with dates, to pass% values from the corresponding nodes to these dates.

For example the date 05/09/2016 would be before the date 06/09/2016 and so would pass the values of the database to mount a Activity correctly.

I do not know if I explained very well, I'll leave the prints of the app, which I have for now to improve the visualization.

Thank you in advance.

    
asked by anonymous 05.09.2016 / 00:38

1 answer

1

I do not know if I understand right, but you seem to have an array of% s of containing% s and you want to sort this array.

If I have correctly understood your question, how about doing this?

public static String[] ordenarDatas(String[] entrada) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    sdf.setLenient(false);
    Date[] dates = new Date[entrada.length];
    for (int i = 0; i < entrada.length; i++) {
        try {
            dates[i] = sdf.parse(entrada[i]);
        } catch (ParseException e) {
            throw new IllegalArgumentException(entrada[i], e);
        }
    }
    Arrays.sort(dates);
    String[] resultado = new String[entrada.length];
    for (int i = 0; i < entrada.length; i++) {
        resultado[i] = sdf.format(dates[i]);
    }
    return resultado;
}

The% required% are these:

import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import java.text.ParseException;
import java.text.SimpleDateFormat;

And then you could use it like this:

protected void populateViewHolder(RoomViewHolder viewHolder, EscapeRoom model, int position) {
    String[] datasBancoDeDados = ordenarDatas(new String[] {model.getData()});
}

See here an example working on ideone .

The given example creates a new array of String and returns it, without changing the original array. However, if what you wanted was to change the original array, and not create a new array, then just change that:

    Arrays.sort(dates);
    String[] resultado = new String[entrada.length];
    for (int i = 0; i < entrada.length; i++) {
        resultado[i] = sdf.format(dates[i]);
    }
    return resultado;

So:

    Arrays.sort(dates);
    for (int i = 0; i < entrada.length; i++) {
        entrada[i] = sdf.format(dates[i]);
    }
    return entrada;

And it will override the given array and return the same array received in the parameter. See here this working on ideone .

    
05.09.2016 / 01:00