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.

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.

package com.jeejava.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.setTime(date);
		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;
	}

}

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

package com.jeejava.date;

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());
		System.out.println(response);
		
		// 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);
		System.out.println(response);
		
		// Test 3
		startDate = new GregorianCalendar(2014, Calendar.FEBRUARY, 12).getTime();
		endDate = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
		response = CompareDateWithoutTime.compareTwoDates(startDate, endDate);
		System.out.println(response);
	}

}

Output

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.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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