Filtering Dates and obtaining Dates in java

3

I have a list of objects and each has a date type calendar . I want to create a filter given two dates that I search for all objects between those dates.

I would also like to create a method that calculates me given today's date which is the previous month or the previous week.

EDIT

is an android application, I have a spinner where I have as option, {today, yesterday, previous week, previous month, yearly} selecting one of these should filter the date according to the ranges and second change a textView saying of which date to which date is being filtered

Calendar actual = GregorianCalendar.getInstance();
//fecha inicio    
Calendar c1 = GregorianCalendar.getInstance();
//fecha Fin
    public void selectedIntervalo(String intervalo){

        switch (intervalo){

            case "Ir a Hoy":
                datefilter(actual, c1);
                break;
            case "Vista hayer":
                c1.add(Calendar.DATE,-1);
                actual.add(Calendar.DATE,-1);
                c1.add(Calendar.HOUR,24);
                actual.add(Calendar.HOUR,-24);
                datefilter(actual, c1);
                break;
            case "Vista Semana Anterior":
                actual.add(Calendar.WEEK_OF_YEAR,-1);
                c1.add(Calendar.WEEK_OF_YEAR,-1);
                datefilter(actual, c1);
                break;
            case "Vista Mensual":
                actual.add(Calendar.MONTH,-1);
                c1.add(Calendar.MONTH,-1);
                datefilter(actual,c1);
                break;
            case "Vista Trimestral":

                break;
            case "Vista Anual":

                break;
            case "Personalizar":

                break;
            default:
                fechaActual();
                break;
        }
    }

    public String datefilter(Calendar date, Calendar i){


        SimpleDateFormat formateador = new SimpleDateFormat("dd/MM");

        return "Del: " +formateador.format(date)+" hasta el "+formateador.format(i);
    }

I still need to quarterly annual but the dates do not come out as I would like a serious example if I say for the previous month considering that today is 14/01/2015 should I say Del: 01/11/2014 until 31/11 / 2014

    
asked by Brian Vega 14.01.2016 в 18:07
source

4 answers

4

To calculate the start and end of the previous month you must first subtract a month from the calendar object, then using getActualMinimum and getActualMaximum you get the first and the last day of the month respectively.

Here is a complete online example: link

The code goes something like this:

// obtenemos la fecha
Calendar fecha = Calendar.getInstance();
// restamos un mes
fecha.add(Calendar.MONTH, -1);
// calculamos el primer dia del mes anterior
Calendar inicioMesAnterior = (Calendar) fecha.clone(); 
inicioMesAnterior.set(Calendar.DAY_OF_MONTH, inicioMesAnterior.getActualMinimum(Calendar.DAY_OF_MONTH));
// calculamos el ultimo dia del mes anterior
Calendar finMesAnterior = (Calendar) fecha.clone();
finMesAnterior.set(Calendar.DAY_OF_MONTH, inicioMesAnterior.getActualMaximum(Calendar.DAY_OF_MONTH));

You must bear in mind that in this example, since I am cloning the date, the time will not be neither 00:00 nor 23:59 respectively. But in the online example above add a couple of functions that solve this problem (reset the hour, minute, second and millisecond values)

Original Answer:

Calendar already has methods to do both

Add / Reduce one hour, one month, one day, etc:

Calendar cal = modelo.getFecha(); // este es tu objecto
cal.add(Calendar.MONTH, -1); // valores positivos para sumar

Verify a date in a range:

Calendar inicioRango = ...; // fecha de inicio
Calendar finRango    = ...; // fecha de fin
Calendar valor       = ...; // fecha a comparar
if (inicioRango.compareTo(valor) <= 0 &&
      finRango.compareTo(valor) >= 0) {
   // valor esta entre inicioRango y finRango
}

You can see on the documentation of Calendar the different options of the add function.

link

    
answered by 14.01.2016 в 19:00
1

To make things easier when you filter, you can use Lambdas , but you'll need to make the property you want to filter not private . For example:

public class User {
    private String name;
    Calendar birthDate;
    private String address;
    private String phone;
    private String email;

    /* Constructores, getters y setters */
}

If you notice the field birthDate I have not made it private, this is because I am going to filter by that field. Now let's see how we filter by a range of dates: between 01-01-1990 and 31-12-1992 :

Calendar after = Calendar.getInstance();
after.setTime(fmt.parse("01-01-1990"));
Calendar before = Calendar.getInstance();
before.setTime(fmt.parse("31-12-1992"));

List<User> filtered = users.stream().filter(u -> 
                                u.birthDate.after(after) && u.birthDate.before(before))
                                .collect(Collectors.toList());
    
answered by 18.01.2016 в 19:47
0

// Intersection of two sets of dates

try {

        boolean interseccionBoolean = false;

SimpleDateFormat format = new SimpleDateFormat ("dd / MM / yyyy");

        Date fechaDesde = formatea.parse("05/05/2017");
        Date fechaHasta = formatea.parse("10/05/2017");            

        //Fechas de corte 

        Date CI = formatea.parse("10/04/2017");
        Date CF = formatea.parse("20/04/2017");

        // Para los casos que se necesite extremos infinitos
        // Date corteDesde = null;
        // Date corteHasta = null;

        corteHasta = (corteHasta == null) ? fechaHasta : corteHasta;
        corteDesde = (corteDesde == null) ? fechaDesde : corteDesde;

        if (!interseccionBoolean && fechaDesde.compareTo(corteDesde) < 0 && fechaHasta.compareTo(corteHasta) > 0) {
            //System.out.print("Caso 1 -> ");
            fechaDesde = corteDesde;
            fechaHasta = corteHasta;
            interseccionBoolean = true;
        }
        if (!interseccionBoolean && fechaDesde.compareTo(corteDesde) > -1 && fechaHasta.compareTo(corteHasta) < 1) {
            //System.out.print("Caso 2 -> ");
            interseccionBoolean = true;
        }

        if (!interseccionBoolean && fechaDesde.compareTo(corteDesde) < 1 && fechaHasta.compareTo(corteHasta) < 1 && fechaHasta.compareTo(corteDesde) > -1) {
            //System.out.print("Caso 3 -> ");
            fechaDesde = corteDesde;
            interseccionBoolean = true;
        }

        if (!interseccionBoolean && fechaDesde.compareTo(corteDesde) > -1 && fechaHasta.compareTo(corteHasta) > -1 && fechaDesde.compareTo(corteHasta) < 1) {
            //System.out.print("Caso 4 -> ");
            fechaHasta = corteHasta;
            interseccionBoolean = true;
        }

        if (interseccionBoolean) {
            System.out.print("Fecha INI " + fechaDesde.toString() + "  ** -- ** Fecha FIN " + fechaHasta.toString());
        } else {
            System.out.print("Interseccion CERO no hay nada que evaluar");
        }

    } catch (ParseException e) {
        //System.out.print("error");
    }
    
answered by 14.06.2017 в 22:51
0

this is the correct way:

Calendar cal = new GregorianCalendar();
Calendar c1 = GregorianCalendar.getInstance();
c1.add(Calendar.MONTH, -1);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
dateFormat.setTimeZone(cal.getTimeZone());
String strDate = dateFormat.format(cal.getTime());
System.out.println(strDate);
    
answered by 24.10.2017 в 18:40