Posted In: Date, Java Core

Comparing two Dates without the time portion

Techniques used

1. JODA Time DateTimeComparator

<dependency>
	<groupId>joda-time</groupId>
	<artifactId>joda-time</artifactId>
	<version>2.9.9</version>
</dependency>

2. Apache Commons DateUtils

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.5</version>
</dependency>

3. JDK 8 LocalDate

4. Below JDK 8 DateFormat

 

package com.example.java.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.DateTimeComparator;
import org.junit.Test;

public class DateCompare2 {

	@Test
	public void compare1() throws Exception {
		// date1
		Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
		        .parse("2017-08-13 12:10:30");

		// date1
		Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
		        .parse("2017-08-13 10:11:30");


		// JODA Time DateTimeComparator
		DateTimeComparator dtc = DateTimeComparator.getDateOnlyInstance();
		System.out.println(dtc.compare(date1, date2));


		// Apache commons
		System.out.println(DateUtils.isSameDay(date1, date2));


		// JDK 8 LocalDate
		LocalDate localdate1 = date1.toInstant().atZone(ZoneId.systemDefault())
		        .toLocalDate();
		LocalDate localdate2 = date2.toInstant().atZone(ZoneId.systemDefault())
		        .toLocalDate();
		System.out.println(localdate1.compareTo(localdate2));


		// Below JDK 8 java.util.Date
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date3 = df.parse(df.format(date1));
		Date date4 = df.parse(df.format(date2));
		System.out.println(date3.compareTo(date4));
	}
}

by , on August 24th, 2017

  • Categories