This tutorial shows how to compare date without time in Java between two dates. Sometimes we need to compare two dates in our Java based applications and if we need to compare only date part without time part for accurate results then we need to first remove the time part from the actual date and perform caparison.

Here is an example that will show you how to remove time part from the actual date and perform comparison. This example will tell you if one date is before, after or equal to another date.


Knowledge of Java

Java version 1.6 or 1.7

Example with Source Code

In the below comparison code example we retrieve only the date part using Java’s Calendar instance. So we set 0 for time part in the calendar instance and return the date. Then we check whether one date is after, before or equal to another date.

import java.util.Calendar;
import java.util.Date;
public class CompareDateWithoutTime {
	public static String compareTwoDates(Date startDate, Date endDate) {
		Date sDate = getZeroTimeDate(startDate);
		Date eDate = getZeroTimeDate(endDate);
		if (sDate.before(eDate)) {
			return "Start date is before end date";
		if (sDate.after(eDate)) {
			return "Start date is after end date";
		return "Start date and end date are equal";
	private static Date getZeroTimeDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		date = calendar.getTime();
		return date;

Testing the Compare Date Class

Creating Test Class

We create below main class to test the above date comparison class.

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class TestComparDateWithoutTime {
	public static void main(String[] args) {
		// Test 1
		String response = CompareDateWithoutTime.compareTwoDates(new Date(), new Date());
		// Test 2
		Date startDate = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
		Date endDate = new GregorianCalendar(2014, Calendar.FEBRUARY, 12).getTime();
		response = CompareDateWithoutTime.compareTwoDates(startDate, endDate);
		// Test 3
		startDate = new GregorianCalendar(2014, Calendar.FEBRUARY, 12).getTime();
		endDate = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
		response = CompareDateWithoutTime.compareTwoDates(startDate, endDate);


Start date and end date are equal
Start date is before end date
Start date is after end date

In the above output we got the expected output from the example on compare date without time in Java.

Source Code

You can download source code.

Thanks for reading.


Leave a Reply

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