Comparing date with next object date in Arraylist not working as expected

compare date with current date in java
compare date with current date in java 8
how to compare current date and time with another date and time in android
java check if date is greater than today
how to compare two string dates in java
java compare dates without time
how to compare two dates in java
java compare time only

I've a list of records, where each record has date objects inside it. I'm checking that the first record should have previous dates than the second, and second record dates should be less than 3rd record and so on.. Here is my code..

for(int i = 0; i < machines.size(); i++) {
        for(int j = i + 1; j < machines.size(); j++) {

            if((machines.get(j).getStrt_Dt().compareTo(machines.get(i).getStrt_Dt()) 
                    * machines.get(i).getStrt_Dt().compareTo(machines.get(j).getStrt_Dt()) >= 0)
                ||
                (machines.get(j).getStrt_Dt().compareTo(machines.get(i).getStrt_Dt()) 
                        * machines.get(i).getStrt_Dt().compareTo(machines.get(j).getStrt_Dt()) >= 0)) {

                throw new Exception("Dates are not as per criteria..");

            }

        }
    }

My dates that are coming from the database is:

  STRT_DT    END_DT
 ---------- ----------     
 2014-01-01 2014-12-31
 2013-01-01 2013-02-01 (Here the second record is having the date less than first record), this should fail 
 2016-01-01 2016-12-31
 2017-01-01 2017-12-31
 2018-01-01 2018-02-01

Am I missing anything? Any help would be greatly appreciated..

You’re over-complicating it. It’s enough to check pairwise entries since if a < b are in the right order and b < c are in the right order, then you already know that a < c are also in the right order.

for(int i = 0; i < machines.size() - 1; i++) {
    if (! machines.get(i).getEnd_Dt().before(machines.get(i + 1).getStrt_Dt())) {
        throw new IllegalStateException("Dates are not in chronological order");
    }
}

I am using "not before" to mean "on or after". Or to put it another way, I am requiring each start date to come stricty before the next start date, and if it doesn’t, I throw the exception. Edit: I didn’t know how to get the end date from your object type, so please substitute the correct getter call where I wrote getEnd_Dt().

If you additionally need to check that each machine has start date and end date in the right order (using the enhanced for loop):

for (Machine m : machines) {
    if (m.getEnd_Dt().before(m.getStrt_Dt())) {
        throw new IllegalStateException("Dates are not in chronological order");
    }
}

As an aside, Java naming conventions don’t use underscores in names (except in a CONSTANT_NAME), so prefer getStrtDt over getStrt_Dt. Or even better, getStartDate.

That said, Embid123 is correct, you should see if you can replace Date with LocalDate. The Date class has design problems and is long outdated. And despite its name it doesn’t represent a date, but a point in time. LocalDate is part of java.time, the modern Java date and time API, which is so much nicer to work with.

The other thing you need is to have your database query sort the entries by start date, then you know you get them in the right order.

What went wrong in your code?

First, your code is complicated on the border of the unreadable.

Next, when two entries i and j have start dates in the wrong order, that is, the j date is earlier than the i date, then machines.get(j).getStrt_Dt().compareTo(machines.get(i).getStrt_Dt()) is negative and machines.get(i).getStrt_Dt().compareTo(machines.get(j).getStrt_Dt() is positive. It’s really the same comparison, only reversed. So the product will be negative, your >= 0 condition will be false and you will not throw the exception.

Only if two entries have the exact same date (down to the millisecond), compareTo returns 0, the product is 0, >= 0 will be true and your exception will be thrown.

Java Date & Time: SimpleDateFormat, Current Date & Compare, Java provides a Date class under the java.util package, The package provides several Display Current Date in Java; SimpleDateFormat: Parse and Format Dates; Compare Dates Example You can use the Date object by invoking the constructor of Date class as follows: Prev · Report a Bug · Next. Comparing two ArrayList objects using containsAll() method. October 4, 2016 SJ Collection 0

Building Websites with the ASP.NET Community Starter Kit, As expected, most of the work here is for setting up the display of the control. to display information and not select a specific date, we turn off the next and This will allow us to modify the content of each date cell in the calendar table. If they do not, you must provide an object implementing IComparer for the ArrayList to  How to compare two ArrayList for equality in Java? Java 8 Object Oriented Programming Programming You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.

Are you using LocalDate? I think it is a good choice for comparing dates. It is since Java 8.

    package sample;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class LocalDateTest {

    public static void main(String[] args) {


        //of(year, month, day)
        LocalDate date1 = LocalDate.of(2018, 11, 11);

        LocalDate date2 = LocalDate.of(2018, 11, 14);

        long daysBetween = ChronoUnit.DAYS.between(date1, date2);

        System.out.println(daysBetween);
    }
}

LocalDate hasn't got any public constructor, you create an object via static factory method. By the use of enum ChronoUnit, you get a long value representing days, weeks, or years from one date do second date. If you want to e.g. calculate weeks between, simply replace DAYS with WEEKS.

Now comparing dates is simple, if the value is negative, the first date exceeds the second one.

Documentation of LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

Compare Dates in Java, The following are the methods to compare dates in java. Using Date.compareTo()​: Steps involved: Create an object for SimpleDateFormat class initialising it with the format interview preparation course with premium videos, theory, practice problems, Next. last_page LinkedList descendingIterator() method in Java with​  The implementation of an ArrayList's contains method uses the equals() method from the Object class to evaluate if the object is in the list or not. This is what you could do In class Person override the equals and hashCode method.

Object-Oriented Design with UML and Java, class: Employee Since the Consultant class is not part of the Employee hierarchy, then it too must implement a similar compareTo method. ArrayList theProgrammers; should also be changed as it names a concrete class (type) The Java language currently provides the GregorianCalendar class to support dates. How to Compare Two Dates in Java. There are various ways to compare Java dates. Internally, a date is represented as a (long) point in time -- the number of milliseconds that have elapsed since January 1 1970. In Java, Date is an object,

How to compare two ArrayLists in Java, Learn to compare two arraylists in Java with simple examples. We will first test if two arraylists are equal or not then find the difference between lists. Love computers, programming and solving everyday problems. getText()); }[java]​Expected result: [ Ranjit Nayak , ranjti Nyak , shenoy attorney ] Actual result using my  Kind of, yes. To be more precise: Comparator.comparing creates a Comparator, which can be used to sort a collection or stream. If you don't provide a Comparator to the sorting method, it will rely on the natural ordering of the elements of the collection instead.

ArrayList, The constant factor is low compared to that for the LinkedList implementation. Constructs an empty list with the specified initial capacity. Following is the declaration for java.util.Date.compareTo() method. public int compareTo(Date anotherDate) Parameters. anotherDate − date to be compared to. Return Value. 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date

Comments
  • Cannot understand why your if statement has the same condition ORed twice?
  • i * i > 0, even if i = -1.
  • Because my first record i would be checking with second record j
  • Is it enough that start dates come in the right order? Or do you need to check for overlaps in time too? I mean where one end date would come after the following start date.
  • Since you have an ArrayList you could also use a listIterator() to get compare the next() and the previous() date-pairs.
  • Thank you. But, I need to validate both start date as well as end date should be less than the next object date.. Do I need to add multiple conditions?
  • Can you please modify the example if possible .. I'm not able to get it..
  • Thanks first of all.. But You are just checking the start date should be less than end date.. I requested you that the start date and end date of the first day should be less than start day and end day of the next object in the list. Hence both should be compared with the next level.
  • Just use the second loop too. When you have checked that the start date of the first date is not later than the end date, and the end date is before the next start date, and that start date is also before or on the corresponding end date, then if follows that both start and end date of the first thingie are before both start and end date of the second thingie. And so forth for the entire list.
  • I'm not using LocalDate..Its Java.util.Date and this comparision should happen between list of objects
  • This Answer does not address the Question. The Question asked about working a with a list of items, each having a pair of dates. The Question asked about comparing the pairs of dates, not elapsed days.