Check if two objects of the class java.util.calendar point to the same day without taking into account the time

-1

I'm trying to compare two dates stored in calendar objects. At the time of seeing if they are equal or minor, or not, I have no problem, the difficulty arises when some of those calendar objects have a date and time stored, and others do not. What I would like to know is if there is a way to verify if 2 calendars have the same date without taking into account the time

I have this code:

    Calendar cal = Calendar.getInstance();
    cal.set(2018, 1, 28, 7, 4, 0);

    if(cal.equals(Calendar.getInstance())){
        System.out.println("hoy");
    }
    
asked by Arturo Ruiz Pascual 28.02.2018 в 22:06
source

1 answer

0

You can convert the calendar to date and format it and only have the date without time and then that date convert it back to calendar type for example:

package javaapplication2;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author SoftMolina
 */
public class CalendarDate {

    public static void main(String[] args) {
        try {
            //Convertimos Calendar a Date
            Calendar calendar = Calendar.getInstance();
            Calendar calendar2 = Calendar.getInstance();

            Date dateCalendar = calendar.getTime();
            Date dateCalenda2 = calendar.getTime();

            System.out.println(dateCalendar);

            //Damos formato a la fecha
            SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");

            String dateS = sdf.format(dateCalendar);
            Date dateD = sdf.parse(dateS);

            String dateS2 = sdf.format(dateCalenda2);
            Date dateD2 = sdf.parse(dateS2);

            System.out.println(dateD);

            //Convertimos el date calendar
            calendar.setTime(dateD);
            calendar2.setTime(dateD2);

            //Calendar sin tiempo
            System.out.println(calendar);
            System.out.println(calendar2);

            //Comparamos las 2 fechas
            System.out.println(calendar.equals(calendar2));
        } catch (Exception e) {
        }
    }

}

Result:

run:
Resultado comparacion: true
BUILD SUCCESSFUL (total time: 0 seconds)
    
answered by 28.02.2018 / 23:26
source