August 5 2015

Compare two dates in java

Compare two dates in java

Dates can be compared using different ways

1. Comparing using compareTo method

public int compareTo(Date date)

The java.util.Date.compareTo(Date date) method compares two Dates. compareTo method returns 0 if this date is equal to argument date, positive value (>0) if this date is after the argument date and negative value (<0) if this date is before the argument date.

Example


package com.answersz.dateutils;

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

public class CompareTwoDates {

public static void main(String[] args) throws ParseException {

System.out.println("Compare two dates in java");

SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
String dt1 = "04-08-2016";
String dt2 = "07-11-2015";
String dt3 = "07-11-2014";
String dt4 = "07-11-2014";

Date date1 = myFormat.parse(dt1);
Date date2 = myFormat.parse(dt2);
Date date3 = myFormat.parse(dt3);
Date date4 = myFormat.parse(dt4);

System.out.println(date1.compareTo(date2));
System.out.println(date2.compareTo(date1));
System.out.println(date3.compareTo(date4));

}
}

Output

Compare two dates in java
1
-1
0

2. Comparing using before(),after() and equals() methods

public boolean before(Date date)

The java.util.Date.before(Date date) method checks if this date is before the argument date. It returns true the date is before the argument date otherwise false.

public boolean after(Date date)

The java.util.Date.after(Date date) method checks if this date is after the argument date. It returns true if the date is after the argument date otherwise false.

public boolean equals(Object obj)

The java.util.Date.equals(Object obj) method checks if this date is equal to the argument date. It returns true if the date is equal to argument date otherwise false.

Example

package com.answersz.dateutils;

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

public class CompareTwoDates2 {

 public static void main(String[] args) throws ParseException {

 System.out.println("Compare two dates in java");

 SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
 String dt1 = "04-08-2016";
 String dt2 = "07-11-2015";
 String dt3 = "07-11-2014";
 String dt4 = "07-11-2014";

 Date date1 = myFormat.parse(dt1);
 Date date2 = myFormat.parse(dt2);
 Date date3 = myFormat.parse(dt3);
 Date date4 = myFormat.parse(dt4);

 System.out.println(date1.before(date2));
 System.out.println(date2.after(date1));
 System.out.println(date3.equals(date4));

 }
}

Output

Compare two dates in java
false
false
true

 


Copyright © 2014. All rights reserved.

Posted August 5, 2015 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*