How to compare two Date objects using compareTo() method in Java

1 Answer

0 votes
package javaapplication1;

import java.util.Date;

public class JavaApplication1 {
    
    public static void main(String[] args) throws InterruptedException {
  
        Date d1 = new Date();

        Thread.sleep(1000);

        Date d2 = new Date();

        System.out.println("d1: " + d1);
        System.out.println("d2: " + d2);

        int result = d1.compareTo(d2);

        if (result > 0) {
            System.out.println("d1 > d2");
        } else if (result < 0) {
            System.out.println("d1 < d2");
        } else {
            System.out.println("d1 = d2");
        }
    }  
}
   
/*
   
run:
   
d1: Fri Oct 28 19:40:16 IDT 2016
d2: Fri Oct 28 19:40:17 IDT 2016
d1 < d2
   
*/

 



answered Oct 28, 2016 by avibootz

Related questions

2 answers 286 views
1 answer 178 views
1 answer 191 views
1 answer 199 views
1 answer 183 views
1 answer 191 views
...