How to compare dates in Java

1 Answer

0 votes
package javaapplication1;

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

public class Example {
    public static void main(String[] args) {
			
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
           	Date d1 = sdf.parse("17/1/2016");
		    Date d2 = sdf.parse("13/12/2015");
 
		    if (d1.before(d2)) 
                System.out.println(sdf.format(d1) + " is before " + sdf.format(d2));
		    else if (d1.after(d2)) 
			         System.out.println(sdf.format(d1) + " is after " + sdf.format(d2));
                 else 
                     System.out.println(sdf.format(d1) + " is same as " + sdf.format(d2)); 
                               
        } catch (Exception ex) {
                System.out.println(ex.getMessage());
        }
    }
}


/*
run:
 
17/01/2016 is after 13/12/2015
 
*/

 



answered Jan 13, 2016 by avibootz

Related questions

1 answer 259 views
1 answer 187 views
2 answers 159 views
159 views asked Mar 12, 2022 by avibootz
2 answers 216 views
1 answer 310 views
310 views asked Oct 6, 2020 by avibootz
4 answers 304 views
1 answer 146 views
146 views asked Jun 6, 2019 by avibootz
...